Getting the Response of a Asynchronous HttpWebRequest

前端 未结 4 1146
[愿得一人]
[愿得一人] 2020-12-01 02:53

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 respo

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 03:54

    "Even better would be to switch to HttpClient if you're using .NET 4.5 since it's 'natively' async." - absolutely right answer by James Manning. This question was asked about 2 years ago. Now we have .NET framework 4.5, whic provides powerful asynchronous methods. Use HttpClient. Consider the following code:

     async Task HttpGetAsync(string URI)
        {
            try
            {
                HttpClient hc = new HttpClient();
                Task result = hc.GetStreamAsync(URI);
    
                Stream vs = await result;
                StreamReader am = new StreamReader(vs);
    
                return await am.ReadToEndAsync();
            }
            catch (WebException ex)
            {
                switch (ex.Status)
                {
                    case WebExceptionStatus.NameResolutionFailure:
                        MessageBox.Show("domain_not_found", "ERROR",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
                        //Catch other exceptions here
                }
            }
        }
    

    To use HttpGetAsync(), make a new method that is "async" too. async is required, because we need to use "await" in GetWebPage() method:

    async void GetWebPage(string URI)
            {
                string html = await HttpGetAsync(URI);
                //Do other operations with html code
            }
    

    Now if you want to get web-page html source code asynchronously, just call GetWebPage("web-address..."). Even Stream reading is asynchronous.

    NOTE: to use HttpClient .NET framework 4.5 is required. Also you need to add System.Net.Http reference in your project and add also "using System.Net.Http" for easy access.

    For further reading how this approach works, visit: http://msdn.microsoft.com/en-us/library/hh191443(v=vs.110).aspx

    Use of Async: Async in 4.5: Worth the Await

提交回复
热议问题