use*_*636 11 c# httpwebrequest
我有这个简单的函数来获取HTML页面并将其作为字符串返回; 虽然有时我得到404.如果请求成功,我怎么才能返回HTML字符串,并返回类似BadRequest404或任何其他错误状态代码的东西?
public static string GetPageHTML(string link)
{
using (WebClient client= new WebClient())
{
return client.DownloadString(link);
}
}
Run Code Online (Sandbox Code Playgroud)
Dar*_*rov 24
您可以捕获WebException:
public static string GetPageHTML(string link)
{
try
{
using (WebClient client = new WebClient())
{
return client.DownloadString(link);
}
}
catch (WebException ex)
{
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
return "An error occurred, status code: " + statusCode;
}
}
Run Code Online (Sandbox Code Playgroud)
当然,在调用代码中捕获此异常更为合适,甚至不会尝试解析html而不是将try/catch放在函数本身中.
| 归档时间: |
|
| 查看次数: |
25143 次 |
| 最近记录: |