c#中的异步web Post API调用

本文关键字:Post API 调用 web 异步 | 更新日期: 2023-09-27 18:13:12

我写的代码如下:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(qry);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.KeepAlive = false;
request.ContentLength = 0;
byte[] data = Encoding.UTF8.GetBytes(crsAdapterXML.ToString());
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
Stream objStream = request.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
result = Convert.ToString(objReader.ReadLine());

我需要使这个呼叫异步。有谁能帮我一下吗?

c#中的异步web Post API调用

使用HttpWebRequest是一种老式的HTTP请求方式。有一些库可以提供更好的api。

我建议你尝试微软的HttpClient (System.Net.Http)或RestSharp。

可能还有更多,但这些是我认识的,而且没有问题。

两者都提供异步API,因此您可以异步等待响应。

我对HttpWebRequest没有太多的经验,但它似乎也暴露了它的方法的异步变化,如GetResponseAsyncGetRequestStreamAsync