gpt4 book ai didi

c# - 发送 webRequest 时出错

转载 作者:行者123 更新时间:2023-11-29 10:54:36 26 4
gpt4 key购买 nike

尝试在 Xamarin for iOS 中发送一些 WebRequest 时出现此错误。

我想登录一个网站,该网站在 Windows 客户端的 C# visual studio 中完美运行,但对于 iOS,它给了我这个错误。

Unhandled Exception:
MonoTouch.UIKit.UIKitThreadAccessException: UIKit Consistency error: you are calling a UIKit method that can only be invoked from the UI thread.
at MonoTouch.UIKit.UIApplication.EnsureUIThread () [0x00019] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:49
at MonoTouch.UIKit.UITextField.get_Text () [0x00000] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UITextField.g.cs:919
at virtualNAX.virtualNAXViewController.SendPost (IAsyncResult Result) [0x00031] in /Users/Emil/Projects/virtualNAX/virtualNAX/virtualNAXViewController.cs:69
at System.Net.WebAsyncResult.CB (System.Object unused) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebAsyncResult.cs:151

第 68 行是:

Post.Write("email=" + username.Text + "&password=" + password.Text + "&remember=on&redir=index.php%2Fprofile%2F&action=login&submit=+Log+in+");

如果需要,这里是我的所有代码:

public void sendData()
{

HttpWebRequest Web = (HttpWebRequest)WebRequest.Create(dataurl);
Web.ContentType = "application/x-www-form-urlencoded";
var cookies = new CookieContainer();
Web.Method = "POST";
Web.CookieContainer = cookies;
Web.BeginGetRequestStream(new AsyncCallback(SendPost), Web);
}

void SendPost(IAsyncResult Result)
{
HttpWebRequest Web = (HttpWebRequest)Result.AsyncState;
var Post = new StreamWriter(Web.EndGetRequestStream(Result));


Post.Write("email=" + username.Text + "&password=" + password.Text + "&remember=on&redir=index.php%2Fprofile%2F&action=login&submit=+Log+in+");
Post.Close();
Web.BeginGetResponse(new AsyncCallback(GetData), Web);
}


void GetData(IAsyncResult Result)
{
HttpWebRequest Web = (HttpWebRequest)Result.AsyncState;

string forside = new StreamReader(Web.EndGetResponse(Result).GetResponseStream()).ReadToEnd();

forside = WebUtility.HtmlDecode(forside);

if (forside.Contains ("Welcome back")) {
NSUserDefaults.StandardUserDefaults.SetString ("sandt", "logind");
this.PerformSegue ("toMain", this);
} else if (forside.Contains ("<div id=\"login_fail\">")) {
using (UIAlertView alert = new UIAlertView ("Error", "The entered information was incorrect.\n\nPlease try again", null, "OK", null)) {
alert.Show ();
}
} else {
using (UIAlertView alert = new UIAlertView ("Error", "An unexpected error has occured.\n\nPlease try again later", null, "OK", null)) {
alert.Show ();
}
}
}

最佳答案

如果“用户名”和“密码”是 UI 控件,则您无法从后台线程访问它们。在调用方法之前,您需要获取它们的值并将它们存储在类变量中(或将它们作为参数传递)。

关于c# - 发送 webRequest 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18987752/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com