WebClient读取错误页面的内容 [英] WebClient read content of error page

查看:50
本文介绍了WebClient读取错误页面的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个加载页面内容的应用程序.我使用WebClient类.即使服务器返回诸如404、500,...之类的错误,我也需要检索内容.我需要这样的东西:

i have an application that loads the page content. I use the WebClient class. I need to retrieve the contents even when the server returns an error such as 404, 500, ... I need something like this:

WebClient wc = new WebClient();
string pageContent;
try {
    pageContent = wc.DownloadString("http://example.com/page");
}
catch (WebException ex)
{
    pageContent = ex.Response.PageContent; // <-- I need this
}

推荐答案

您可以尝试以下操作:

WebClient wc = new WebClient();
string pageContent;
try {
    pageContent = wc.DownloadString("http://example.com/page");
}
catch (WebException ex)
{
    Stream receiveStream = ex.Response.GetResponseStream();
    Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
    StreamReader readStream = new StreamReader( receiveStream, encode );
    pageContent=readStream.ReadToEnd();
}

这篇关于WebClient读取错误页面的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆