Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the Response of a Asynchronous HttpWebRequest

Tags:

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;    } } 
like image 832
gdp Avatar asked May 12 '12 15:05

gdp


People also ask

How do I get a response to an asynchronous request?

Get Response Async Method System. Net When overridden in a descendant class, returns a response to an Internet request as an asynchronous operation. The task object representing the asynchronous operation. This operation will not block. The returned Task<TResult> object will complete after a response to an Internet request is available.

How do I initiate an asynchronous web request using ThreadPool?

Use HttpWebRequest.BeginGetResponse () to initiate an asynchronous request. Use ThreadPool.RegisterWaitForSingleObject () to register a timeout delegate for unresponsive Web requests.

What happens when you do an Ajax request?

That’s exactly what’s happening when you do an Ajax request. Instead of waiting for the response, the execution continues immediately and the statement after the Ajax call is executed. To get the response eventually, you provide a function to be called once the response was received, a callback (notice something? call back ?).

What is system net web request get response?

System. Net Web Request. Get Response Async Method System. Net When overridden in a descendant class, returns a response to an Internet request as an asynchronous operation.


1 Answers

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;     } } 
like image 73
James Manning Avatar answered Sep 24 '22 12:09

James Manning