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

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

问题描述

我想知道如果theres一个简单的方法来获得一个异步的响应HttpWebRequest的。

我已经看到了这个问题<一href=\"http://stackoverflow.com/questions/9877120/how-do-i-actually-get-the-response-of-an-async-web-request-from-outside-the-meth\">here但所有IM要做的是用它返回相应的响应(这通常是JSON或XML)将字符串中的另一种方法的形式,在那里我可以再分析它/成交。

下面有一些code:

我在这里,我觉得这两个静态方法是线程安全的,因为在传递的所有PARAMS和没有共享的局部变量,该方法使用?

 公共静态无效MakeAsyncRequest(URL字符串,字符串的contentType)
{
    HttpWebRequest的要求=(HttpWebRequest的)WebRequest.Create(URL);
    request.ContentType的contentType =;
    request.Method = WebRequestMethods.Http.Get;
    request.Timeout = 20000;
    request.Proxy = NULL;    request.BeginGetResponse(新的AsyncCallback(ReadCallback),请求);
}私有静态无效ReadCallback(IAsyncResult的asyncResult)
{
    HttpWebRequest的要求=(HttpWebRequest的)asyncResult.AsyncState;
    尝试
    {
        使用(HttpWebResponse响应=(HttpWebResponse)request.EndGetResponse(asyncResult))
        {
            流responseStream = response.GetResponseStream();
            使用(StreamReader的SR =新的StreamReader(responseStream))
            {
                //需要返回此响应
                字符串strContent = sr.ReadToEnd();
            }
       }
       manualResetEvent.Set();
    }
    赶上(异常前)
    {
        扔恩;
   }
}


解决方案

假设的问题是,你有一个很难得到返回的内容,最简单的路径很可能会使用异步/等待,如果你可以用它。更妙的是切换到HttpClient的,如果你正在使用.NET 4.5,因为它是'原生'异步。

使用.NET 4和C#4,你仍然可以用任务来包装这些并使其更容易一点获得最终结果。例如,一种选择会是下面。需要注意的是它具有Main方法阻塞,直到内容字符串是可用的,但在一个真实的场景你任务可能传递到其他的东西或字符串另一ContinueWith关闭它或什么的。

 无效的主要()
{
    VAR任务= MakeAsyncRequest(http://www.google.com,text / html的);
    Console.WriteLine(,task.Result{0}拿到了反应);
}//定义其它的方法和类在这里
公共静态任务&LT;串GT; MakeAsyncRequest(URL字符串,字符串的contentType)
{
    HttpWebRequest的要求=(HttpWebRequest的)WebRequest.Create(URL);
    request.ContentType的contentType =;
    request.Method = WebRequestMethods.Http.Get;
    request.Timeout = 20000;
    request.Proxy = NULL;    任务&LT;&WebResponse的GT;任务= Task.Factory.FromAsync(
        request.BeginGetResponse,
        asyncResult =&GT; request.EndGetResponse(asyncResult)
        (对象),NULL);    返回task.ContinueWith(T =&GT; ReadStreamFromResponse(t.Result));
}私人静态字符串ReadStreamFromResponse(WebResponse的响应)
{
    使用(流responseStream = response.GetResponseStream())
    使用(StreamReader的SR =新的StreamReader(responseStream))
    {
        //需要返回此响应
        字符串strContent = sr.ReadToEnd();
        返回strContent;
    }
}

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

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.

Heres some code:

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

解决方案

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.

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天全站免登陆