c异步http请求
本文关键字:请求 http 异步 | 更新日期: 2023-09-27 18:25:10
我正在尝试对某个服务器进行异步调用,这样主线程就不会因请求而停止。
我创建了这样的请求:
//Create Request
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = method;
request.ContentType = "application/XML";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(data);
request.ContentLength = bytes.Length;
try
{
using (Stream requestStream = request.GetRequestStream())
{
// Send the data.
requestStream.Write(bytes, 0, bytes.Length);
}
request.BeginGetResponse((x) =>
{
using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(x))
{
if (callback != null)
{
callback(response.GetResponseStream());
}
}
}, null);
}
catch (Exception ex)
{
//TODO: Log error
}
但是线程在这个请求中仍然会停止一段时间。特别是在使用的线路上
(Stream requestStream = request.GetRequestStream())
有没有什么方法可以让它完全异步,或者其他更好的方法,这样我们的主线程就不会为这个请求挂起。
using (HttpClient client = new HttpClient())
{
var content = new StringContent(data, Encoding.UTF8, "application/xml");
var response = await client.PostAsync(uri, content);
var respString = await response.Content.ReadAsStringAsync();
}
需要使用异步方法并等待它们。
using (var stream = await request.GetRequestStreamAsync())
{
await stream.WriteAsync(bytes, 0, bytes.Length);
}
这里有一个简单的示例,我正在使用它来发出异步请求。用async keyword
标记您的方法
using (var httpClient = new HttpClient())
{
string requestContent = string.Empty; // JSON Content comes here
HttpContent httpContent = new StringContent(requestContent, Encoding.UTF8, "application/json");
HttpRequestMessage httpRequestMessage = new HttpRequestMessage(Verb, url);
httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpRequestMessage.Content = request.Verb == HttpMethod.Get ? null : httpContent;
response = httpClient.SendAsync(httpRequestMessage);
var responseContent = await response.Result.Content.ReadAsStringAsync();
}