Reading HTML pages with .NET Core

4

Next, I have a code that reads a particular web page:

private string GetCodePage()
{
    WebRequest request = WebRequest.Create(URL);
    WebResponse response = request.GetResponse();
    StreamReader reader = new StreamReader(response.GetResponseStream());

    var codePage = reader.ReadToEnd();

    reader.Close();
    response.Close();

    return codePage;
}

I'm trying to make the same code with .NET Core, but the classes have changed, for example, the WebRequest.GetResponse method no longer exists.

Does anyone know how to read html pages through DotNet Core?

    
asked by anonymous 28.06.2016 / 16:30

2 answers

4

You will have to use the new class HttpClient in System.Net.Http , which is available no Nuget .

A very simple example of how to use:

using(var client = new HttpClient())
{
    var response = await client.GetStringAsync(URL);
    //Existem outras opções aliém do GetStringAsync, aí você precisa explorar a classe
}
    
28.06.2016 / 16:49
1

I was able to solve with the following code:

    private string GetCodePage()
    {
        HttpClient httpClient = new HttpClient();
        var response = httpClient.GetAsync(URL).Result;
        return response.Content.ReadAsStringAsync().Result;
    }
    
28.06.2016 / 18:58