我想知道是否有一种简单的方法来获取异步 httpwebrequest 的响应。
我已经看过这个问题了here https://stackoverflow.com/questions/9877120/how-do-i-actually-get-the-response-of-an-async-web-request-from-outside-the-meth但我想做的就是以字符串的形式将响应(通常是 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;
}
}
假设问题是您很难获取返回的内容,那么最简单的路径可能是使用 async/await(如果您可以使用它)。如果您使用 .NET 4.5,最好切换到 HttpClient,因为它是“本机”异步的。
使用 .NET 4 和 C# 4,您仍然可以使用 Task 来包装它们,并使访问最终结果变得更容易。例如,一种选择如下。请注意,它的 Main 方法会阻塞,直到内容字符串可用为止,但在“真实”场景中,您可能会将任务传递给其他任务或将另一个ContinueWith 串起来或其他什么。
void Main()
{
var task = MakeAsyncRequest("http://www.google.com", "text/html");
Console.WriteLine ("Got response of {0}", task.Result);
}
// Define other methods and classes here
public static Task<string> 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;
Task<WebResponse> task = Task.Factory.FromAsync(
request.BeginGetResponse,
asyncResult => request.EndGetResponse(asyncResult),
(object)null);
return task.ContinueWith(t => ReadStreamFromResponse(t.Result));
}
private static string ReadStreamFromResponse(WebResponse response)
{
using (Stream responseStream = response.GetResponseStream())
using (StreamReader sr = new StreamReader(responseStream))
{
//Need to return this response
string strContent = sr.ReadToEnd();
return strContent;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)