Search code examples
c#webrequest

RestClient works but HttpWebRequest doesn't


This code works:

 var source = "https://jade.io/xml/au-qld-dc.xml";
        
 var client = new RestClient(source);
 var request = new RestRequest(Method.GET);
 IRestResponse resp = client.Execute(request);
 Console.WriteLine(resp.Content);

The xml is retrieved and displayed in the Console. But this code doesn't work:

HttpWebRequest httpsRequest = (HttpWebRequest) WebRequest.Create(source);
httpsRequest.Method = "GET";
var response = httpsRequest.GetResponse();

It throws a 403 (Forbidden) error...

I'd like to know why it doesn't work, because I have some legacy code using WebRequest, and before replacing all that code with RestClient, if there is an easy fix...


Solution

  • Add UserAgent header and it will work.

    var source = "https://jade.io/xml/au-qld-dc.xml";
    HttpWebRequest httpsRequest = (HttpWebRequest)WebRequest.Create(source);
    httpsRequest.Method = "GET";
    httpsRequest.UserAgent = "Test";
    var response = httpsRequest.GetResponse();