由于书本内容较少,自己知识储备量不足,在c#客户端请求http登陆的时候,因为占用ui线程,直接造成卡死(假死),百度谷歌了一堆,还是一脸懵逼,通过在loc论坛询问后,得知用Task.Run可以解决此问题,于是又出来折腾,发现不行,还是因为自己菜啊!
界面:修改按钮点击类为async
private async void button2_Click(object sender, EventArgs e)
{
string user = textBox3.Text;
string pass = textBox4.Text;
string postdata = "user=" + user + "&pass=" + pass;
var result = await AsyncLogin(postdata);
MessageBox.Show(result);
}
请求函数,sendpost函数是处理访问并返回值,代码
private Task<string> AsyncRegister(string postdata)
{
var result = Task.Run(() =>
{
return sendPost(postdata, "http://localhost/admin/login");
});
return result;
}
//请求函数
public string sendPost(string postData, string requestUrlString)
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(postData);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(requestUrlString);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.Timeout = 30000;
Stream newStream = myRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
return reader.ReadToEnd();
}
本文作者:风雪,转载时请注明本文出处:https://www.fxnetw.com/79.html
大帅逼
2020-07-14 Windows10 / Chrome 回复
感觉谷歌比百度靠谱。。