Claudio Masieri
Claudio Masieri

Reputation: 3

Load a json url from Webclient

I want to get data from this json url.

https://viabilita.autostrade.it/traffico-fasce-orarie-cantieri-liguria/all2.json

This data is used from this page:

https://viabilita.autostrade.it/traffico-fasce-orarie-cantieri-liguria/index.html

using (var httpClient = new HttpClient())
{
    var json = await httpClient.GetStringAsync("https://viabilita.autostrade.it/traffico-fasce-orarie-cantieri-liguria/all2.json");

    // Now parse with JSON.Net
} 

If I try to get from webclient I get a totally different string from when I use the browser to get it.

Is perhaps the "strict-origin-when-cross-origin" that cause this? Is it some other header to add to my request?

Thank you

Upvotes: 0

Views: 136

Answers (1)

Karl-Johan Sjögren
Karl-Johan Sjögren

Reputation: 17522

Per default HttpClient won't send any User-Agent and this will make quite a few sites suspious. I tried the same request without setting an User-Agent header and it returned an HTML document instead.

So you need to add a User-Agent header and it will probably work (and to be a good sport, add a user-agent that identifies your application).

using (var httpClient = new HttpClient())
{
    httpClient.DefaultRequestHeaders.Add("User-Agent", "MyApp/1.0");
    var json = await httpClient.GetStringAsync("https://viabilita.autostrade.it/traffico-fasce-orarie-cantieri-liguria/all2.json");

    // Now parse with JSON.Net
} 

Upvotes: 2

Related Questions