Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad Request 400 - protocol error on a valid url - Webclient

Tags:

c#

webclient

I am trying to parse this page (http://www.coleparmer.co.uk/Product/Turb_Std_Hach_2100q_Kit/WZ-99900-47) using webclient and am having no luck.

 var client = new WebClient();
  var html = client.DownloadString("http://www.coleparmer.co.uk/Product/Turb_Std_Hach_2100q_Kit/WZ-99900-47");
like image 347
vishnu Avatar asked Dec 05 '22 07:12

vishnu


2 Answers

The appropriate headers needs to be set.

try
{
    string html;
    using (WebClient client = new WebClient())
    {
        client.Headers.Add("Accept-Language", " en-US");
        client.Headers.Add("Accept", " text/html, application/xhtml+xml, */*");
        client.Headers.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
        html = client.DownloadString("http://www.coleparmer.co.uk/Product/Turb_Std_Hach_2100q_Kit/WZ-99900-47");
    }
}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
    {
        var resp = (HttpWebResponse)ex.Response;
        if (resp.StatusCode == HttpStatusCode.NotFound) // HTTP 404
        {
            //Handle it
        }
    }
    //Handle it
}
like image 70
Charls Avatar answered Dec 19 '22 09:12

Charls


It requires a Header.

WebClient client = new WebClient();
client.Headers["Content-Type"] = "application/json;charset=UTF-8";    
like image 29
maxspan Avatar answered Dec 19 '22 11:12

maxspan