mhyassin
mhyassin

Reputation: 134

How to do a HTTP GET request using async and await

I'm trying to create a function that takes a url as a parameter and returns the GET Response from it, it just give me an error in the WebResponse responseObject intialization line

The exception is An exception of type 'System.Net.ProtocolViolationException' occurred in mscorlib.ni.dll but was not handled in user code

public static async Task<string> get(string url)
{
    var request = WebRequest.Create(new Uri(url)) as HttpWebRequest;
    request.Method = "GET";
    request.ContentType = "application/json";
    WebResponse responseObject = await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, request);
    var responseStream = responseObject.GetResponseStream();
    var sr = new StreamReader(responseStream);
    string received = await sr.ReadToEndAsync();

    return received;
}

Upvotes: 0

Views: 17177

Answers (2)

Paul Annetts
Paul Annetts

Reputation: 9604

You can't set ContentType for a GET request as you aren't sending any data up to the server.

Content-Type = The MIME type of the body of the request (used with POST and PUT requests).

This is the source of your ProtocolViolationException.

It looks like you want to set the Accept header instead.

Accept = Content-Types that are acceptable for the response

(As per Wikipedia)

Try changing your code to:

request.Accept = "application/json";

Upvotes: 6

Jammer
Jammer

Reputation: 10208

Try it with HttpClient instead like this:

    public async Task<List<MyClass>> GetMyClassAsync(
    CancellationToken cancelToken = default(CancellationToken))
    {
        using (HttpClient httpClient = new HttpClient())
        {
            var uri = Util.getServiceUri("myservice");
            var response = await httpClient.GetAsync(uri, cancelToken);
            return (await response.Content.ReadAsAsync<List<MyClass>>());
        }
    }

Upvotes: 3

Related Questions