我想知道是否有一种简单的方法来获取异步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;
}
}