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

痞子三分冷 提交于 2019-12-17 20:28:27

问题


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");

回答1:


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
}



回答2:


It requires a Header.

WebClient client = new WebClient();
client.Headers["Content-Type"] = "application/json;charset=UTF-8";    


来源:https://stackoverflow.com/questions/22623664/bad-request-400-protocol-error-on-a-valid-url-webclient

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!