获取异步 HttpWebRequest 的响应 [英] Getting the Response of a Asynchronous HttpWebRequest

查看:40
本文介绍了获取异步 HttpWebRequest 的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种简单的方法来获取异步 httpwebrequest 的响应.

Im wondering if theres an easy way to get the response of an async httpwebrequest.

我已经看过这个问题 here 但我要做的就是以字符串的形式将响应(通常是 json 或 xml)返回到另一种方法,然后我可以解析它/处理相应地.

I have already seen this question here but all im trying to do is return the response (which is usually json or xml) in the form of a string to another method where i can then parse it/ deal with it accordingly.

这里有一些代码:

我这里有这两个静态方法,我认为它们是线程安全的,因为所有参数都被传入并且没有这些方法使用的共享局部变量?

I have these two static methods here which i think are thread safe as all the params are passed in and there are no shared local variables that the methods use?

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,因为它是本机"异步的.

Assuming the problem is that you're having a hard time getting to the returned content, the easiest path would likely be using async/await if you can use it. Even better would be to switch to HttpClient if you're using .NET 4.5 since it's 'natively' async.

使用 .NET 4 和 C# 4,您仍然可以使用 Task 来包装它们,并使其更容易访问最终结果.例如,一种选择如下.请注意,在内容字符串可用之前,它的 Main 方法会阻塞,但在真实"场景中,您可能会将任务传递给其他内容,或者将另一个 ContinueWith 字符串从它或其他内容中删除.

Using .NET 4 and C# 4, you can still use Task to wrap these and make it a bit easier to access the eventual result. For instance, one option would be the below. Note that it has the Main method blocking until the content string is available, but in a 'real' scenario you'd likely pass the task to something else or string another ContinueWith off of it or whatever.

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;
    }
}

这篇关于获取异步 HttpWebRequest 的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆