zoukankan      html  css  js  c++  java
  • System.Net.HttpWebRequest.GetResponse() 远程服务器

    WebException 服务器状态码错误,比如500服务器内部错误

    现象

    我们编码实现请求一个页面时,请求的代码类似如下代码:

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strUrl);
    req.UserAgent = "MSIE6.0";
    req.Method = "GET";
    HttpWebResponse res = (HttpWebResponse)req.GetResponse();
    StreamReader sr = new StreamReader(res.GetResponseStream(), strEncode);
    strHtml = sr.ReadToEnd();
    sr.Close();
    res.Close();

    但是,如果我们请求的这个页面正好是一个有异常发生的页面,或者不存在的页面。我们上面的代码就会在

    req.GetResponse();

    这里抛出异常:远程服务器返回错误: (500) 内部服务器错误。

    我们通过上面的代码,是不能得到错误发生时候的页面源代码的。

    分析原因:

    (HttpWebResponse)req.GetResponse(); 这行代码中做了如下一件事情:

    当服务器段ASP.net程序有 Exception 发生时,客户端应用程序接受了HTTP 协议错误后。把这个HTTP 协议错误转换成 Status 设置为 WebExceptionStatus.ProtocolError 的 WebException,并且把这个异常throw出来。

    解决问题

    那如果我们想获得错误发生时候服务器段错误页面的源代码该如何做呢?

    其实非常非常简单的做法,我们用下面的代码就不论错误发生与否,都可以获得服务器段页面的源代码。

     HttpWebResponse res;
    try
    {
    res = (HttpWebResponse)req.GetResponse();
    }
    catch (WebException ex)
    {
    res = (HttpWebResponse)ex.Response;
    }
    StreamReader sr = new StreamReader(res.GetResponseStream(), strEncode);
    strHtml = sr.ReadToEnd();
    当异常发生事后,WebException 中不仅有 StatusCode 标志着 HTTP 的错误代码,而且它的 Response 属性还包含由服务器发送的 WebResponse,来指示遇到的实际 HTTP 错误。

     --发现文件可以下载,但是发现下载后的文件没有内容

    在下面加上红色这句:


    HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create(url);//?act=writePayInfo&payphone=" + num
            Request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
            WebResponse Response = Request.GetResponse();

    --文件可下载,且可以打开

    参考:https://blog.csdn.net/atceedsun/article/details/44855799

               https://blog.csdn.net/rrzhaobaojun/article/details/25769581

  • 相关阅读:
    大约PCA算法学习总结
    内部硬盘的硬件结构和工作原理进行了详细解释
    DWZ使用注意事项
    cocos2d-x 在XML分析和数据存储
    HTML精确定位:scrollLeft,scrollWidth,clientWidth,offsetWidth完全详细的说明
    hdu 1114 Piggy-Bank
    getResources()方法
    人机博弈-吃跳棋游戏(三)代移动
    Oracle 11g client安装和配置。
    的微信公众号开发 图灵机器人接口允许调用自己的微通道成为一个智能机器人
  • 原文地址:https://www.cnblogs.com/wangfuyou/p/9647535.html
Copyright © 2011-2022 走看看