我想知道是否有一种简单的方法来获得异步 httpwebrequest 的响应。
我已经在这里看到了这个问题,但我想做的只是将响应(通常是 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;
}
}