Search code examples
c#restrestsharp

How make RestSharp request like a browser request?


Surprisingly I noticed that the page that is obliged to share public API (https://danepubliczne.imgw.pl/api/data/hydro/), seems to block the RestSharp request but at the same time URL at the browser return results more or less correctly... There is no one pattern of how request is blocked and I don't know if for sure that is intentional. Still, quite often Restharp requests are unsuccessful. The request ends with a timeout or one of 500s errors. At the same time, the request for the chrome browser works in most cases correctly. Below is the code that is used to get a response from that service

RestClient client;
RestRequest request;
client = new RestClient("https://danepubliczne.imgw.pl/api/data/hydro/");
request = new RestRequest(Method.GET);
request.AddHeader("Accept", "*/*");
response = client.Execute(request);

So could you recommend to me how to make a Restsharp request looks like a request from example the last version of the chrome browser?


Solution

  • You need to add headers to your request. It seems that at least User-Agent is required. Try something like this:

    var request = new RestRequest(...);
    ...
    request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36");