C#下载网页(包含网页错误的情况)

c#
2015-05-02 0 703
C#下载网页(包含网页错误的情况)

C#下载网页,即使网页404或者500错误

public static string GetWebPageAsString(string url)
{
    HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest.Create(url);
    HttpWebResponse httpWebResponse = null;
    string xml = "";
    try
    {
        httpWebResponse = (HttpWebResponse) httpWebRequest.GetResponse();
    }
    catch (WebException exception)
    {
        if (exception.Status == WebExceptionStatus.ProtocolError)
        { //get the response object from the WebException
            httpWebResponse = exception.Response as HttpWebResponse;
            if (httpWebResponse == null){ return "<Error />";}
        }
    }
    Stream stream = httpWebResponse.GetResponseStream();
    StreamReader streamReader = new StreamReader(stream, Encoding.ASCII);
    xml = streamReader.ReadToEnd();
    //streamReader.Close();
    if (httpWebResponse.StatusCode != System.Net.HttpStatusCode.OK)
    {
        throw new Exception(xml);
    }
 
    return xml;
}

遇见资源网 c# C#下载网页(包含网页错误的情况) http://www.ox520.com/12285.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务