0

I used the below code for making a HttpWebrequest and read response from server.

private async Task<bool> ReadUrlAsync() { var request = HttpWebRequest.Create(request_url) as HttpWebRequest; request.Accept = "application/json;odata=verbose"; var factory = new TaskFactory(); var task = factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null); var response = await task; Stream responseStream = response.GetResponseStream(); string data; using (var reader = new System.IO.StreamReader(responseStream)) { data = reader.ReadToEnd(); } responseStream.Close(); return true; } 

But i am not sure about is this is the right way , since i can see

var response = await task 

and one TaskFactory instance inside method. So is any way to write this code without Taskfactory or a seperate await inside the function

2 Answers 2

2

Awaiting a FromAsync task is fine. I usually create an extension method so that the FromAsync is in its own method, but it does almost exactly the same thing as you're doing here (the standard pattern is to use Task.Factory.FromAsync instead of new TaskFactory().FromAsync).

Note that a more modern approach is to use HttpClient from NuGet, which simplifies the code significantly:

async Task<bool> ReadUrlAsync() { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose"); using (var response = await client.GetAsync(request_url)) { var data = await response.Content.ReadAsStringAsync(); return true; } } } 

I'm assuming that you want the response explicitly, e.g., to check response headers. If you don't need it, you can simplify further:

async Task<bool> ReadUrlAsync() { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose"); var data = await client.GetStringAsync(request_url); return true; } } 
Sign up to request clarification or add additional context in comments.

Comments

1

May this will help you

private void ReadUrlAsync() { var request = HttpWebRequest.Create(request_url) as HttpWebRequest; request.Accept = "application/json;odata=verbose"; request.BeginGetResponse(ResponseCallback, request); } private void ResponseCallback(IAsyncResult asyncResult) { HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult); using (Stream responseStream= response.GetResponseStream()) { string data; using (var reader = new System.IO.StreamReader(responseStream)) { data = reader.ReadToEnd(); } } } 

2 Comments

IS there any request.ReadAsync() kind of extension available.? In case of reading from file we are using .ReadToEndAsync(); so any similar way exists ?
Issuing a GET request on a url and read response from the url

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.