当HttpWebRequest遭遇HTTP500错误
使用IE可以正常访问某一地址,当使用HttpWebRequest访问时,服务器返回500错误,HttpWebRequest会抛出一个WebException,如果IE可以访问,则证明了该页面还是有数据的,解决方法:捕获异常,见下面的代码
try
{
httpRspn = (HttpWebResponse)httpRqst.GetResponse();
}
catch (WebException ex)
{
httpRspn = (HttpWebResponse)ex.Response;
}
{
httpRspn = (HttpWebResponse)httpRqst.GetResponse();
}
catch (WebException ex)
{
httpRspn = (HttpWebResponse)ex.Response;
}
另外一种情况是服务器会返回一个500或者404的错误,如果上面的方法无法解决(在保证资源正确的情况下),设置HttpWebRequest的UserAgent,如
httpRqst.UserAgent = "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; QQDownload 534; TencentTraveler 4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; CIBA; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.2)";