Search code examples
c#visual-studiohttpgetwin-universal-app

GET : Getting an http response in C#


WebRequest req = WebRequest.Create("[URL here]");
WebResponse rep = req.GetResponse();

I wanted some insights into the relevance of the GetResponse method, it appears to deprecated now.

This other method I hacked together gets the job done.

HttpWebRequest request = (HttpWebRequest) WebRequest.Create(String.Format("http://mywebservicehere/dostuff?url=https://www.website.com"));
request.Method = "GET";

using (var response = (HttpWebResponse) (await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{                
    var encoding = ASCIIEncoding.ASCII;
    StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
}

Wanted to know of any alternative methods others may have used? Thanks for the help!


Solution

  • I wanted some insights into the relevance of the GetResponse method, it appears to deprecated now.

    It is not deprecated, in the .NET for UWP, is is an async method.

        WebRequest req = WebRequest.Create("[URL here]");
    
        WebResponse rep = await req.GetResponseAsync();
    

    Wanted to know of any alternative methods others may have used?

    Besides the WebRequest class, there are another 2 HttpClient classes in the Windows Runtime Platform you can use to get a http response.

        var client1 = new System.Net.Http.HttpClient();
    
        var client2 = new Windows.Web.Http.HttpClient();
    

    The System.Net.Http.HttpClient is in the .NET for UWP. The Windows.Web.Http.HttpClient is in the Windows Runtime.