• HttpWebResponse远程服务器返回错误: (500) 内部服务器错误 的解决办法


    在工作中用C#开发了一个小程序,不断访问去请求一个网站的页面,在循环过程中有时会报“远程服务器返回错误: (500) 内部服务器错误”,有时不会,出现的时机也不太一样。开始以为是网站的问题,后来网站是可以正常访问的,那就是自己程序的问题了。

    for (int i = refreshAccount.startNum; i <= refreshAccount.endNum; i++)
    {
          String data2 = urlstr;
          loadBranch2Request = (HttpWebRequest)HttpWebRequest.Create(data2);
          loadBranch2Request.CookieContainer = request2.CookieContainer;
          loadBranch2Response = (HttpWebResponse)loadBranch2Request.GetResponse();
          reader = new StreamReader(loadBranch2Response.GetResponseStream(), Encoding.UTF8);
    
          string result3 = reader.ReadToEnd();
          loadBranch2Response.Close();
          reader.Close();
          …………
    }

    从两个方向找原因,一是HttpWebRequest的正确写法,二是出现上述问题的原因。在查阅了同类问题的解决方法后,大致判断为请求报文的问题。

    两个参考博文如下:

    C#模拟http 发送post或get请求:https://www.cnblogs.com/aaronguo/p/7063790.html

    HttpWebResponse远程服务器返回错误: (500) 内部服务器错误 的解决办法:https://blog.csdn.net/henrycg55/article/details/5330323

    想当然以为用的是get方法, 不用设置loadBranch2Request.ContentType的值,事实上设置Method和ContentType的值却解决了上面的问题。

    loadBranch2Request.Method = "GET";

    loadBranch2Request.ContentType = "text/html;charset=UTF-8";

    for (int i = refreshAccount.startNum; i <= refreshAccount.endNum; i++)
    {
      String data2 = urlstr;
      loadBranch2Request = (HttpWebRequest)HttpWebRequest.Create(data2);
      loadBranch2Request.CookieContainer = request2.CookieContainer;
      loadBranch2Request.Method = "GET";
      loadBranch2Request.ContentType = "text/html;charset=UTF-8";
      loadBranch2Response = (HttpWebResponse)loadBranch2Request.GetResponse();
      reader = new StreamReader(loadBranch2Response.GetResponseStream(), Encoding.UTF8);
    
      string result3 = reader.ReadToEnd();
      loadBranch2Response.Close();
      reader.Close();
       …………
    }

    如果想获取错误页面的源码,可以用如下方法

    参考:https://www.cnblogs.com/cresuccess/archive/2009/12/09/1619977.html

    用下面的代码就不论错误发生与否,都可以获得服务器段页面的源代码。

     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 错误。
  • 相关阅读:
    GB50174-2008《电子信息系统机房设计规范》
    Tickets HDU
    HDU
    [长期更新]题解合集
    网络流/费用流题目总结[持续更新]
    [转载]Maximum Flow: Augmenting Path Algorithms Comparison
    [转载]网络流笔记
    网络流各类算法简单总结与比较
    简单的算法备忘录,个人总结[长期更新]
    训练报告 18春组队04 2014西安全国邀请赛
  • 原文地址:https://www.cnblogs.com/zhaoshizi/p/9217373.html
Copyright © 2020-2023  润新知