如何使用C#进行异步WebRequest

时间:2018-09-24 17:11:57

标签: c# webrequest

我有一个正常的webrequest功能。 我返回了JSON数据,但是响应时间有所不同,有时会在1秒后返回,而在200秒后有时会返回。

当我发送POST数据时,整个GUI都冻结了。

如何使用异步WebRequest处理此问题?

这是我的代码:

WebRequest request = WebRequest.Create("https://" + "192.168.0.1" + "/conf");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = textBox2.Text;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json; charset=UTF-8";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Set login parameters
request.Credentials = new NetworkCredential("1", "123");
// Accpet certificate
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
// Continue at expection
System.Net.ServicePointManager.Expect100Continue = false;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
subEvent = responseFromServer;
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();

0 个答案:

没有答案