【发布时间】:2012-05-12 15:37:51
【问题描述】:
我想知道是否有一种简单的方法来获取异步 httpwebrequest 的响应。
我已经看到了这个问题here,但我所做的只是将响应(通常是 json 或 xml)以字符串的形式返回到另一个方法,然后我可以在其中解析它/相应地处理它.
这里有一些代码:
我在这里有这两个静态方法,我认为它们是线程安全的,因为所有参数都被传入并且这些方法没有使用共享的局部变量?
public static void MakeAsyncRequest(string url, string contentType)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = contentType;
request.Method = WebRequestMethods.Http.Get;
request.Timeout = 20000;
request.Proxy = null;
request.BeginGetResponse(new AsyncCallback(ReadCallback), request);
}
private static void ReadCallback(IAsyncResult asyncResult)
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult))
{
Stream responseStream = response.GetResponseStream();
using (StreamReader sr = new StreamReader(responseStream))
{
//Need to return this response
string strContent = sr.ReadToEnd();
}
}
manualResetEvent.Set();
}
catch (Exception ex)
{
throw ex;
}
}
【问题讨论】:
-
我删除了多余的 manualResetEvent.Set(); 后,您发布的代码运行良好- 你遇到了什么问题?
-
@JamesManning 嗨,是的,这是一个错字,我正在寻找一种更简单的方法来获得结果。您提供的 (Task
) 完全符合要求。我刚刚从同步请求中跳了出来,似乎还有很多事情要做。谢谢
标签: c# asynchronous httpwebrequest httpwebresponse