zoukankan      html  css  js  c++  java
  • HttpWebRequest 远程服务器返回错误: (403) 已禁止

    HttpWebRequest获取页面内容时,得到“远程服务器返回错误: (403) 已禁止。”
    找了些解决方案,补充UserAgent

    req.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; QQWubi 133; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; CIBA; InfoPath.2)";
    

    添加后成功解决,但是不久仍出现此问题,又添加CookieContainer

    httpReq.CookieContainer = new CookieContainer();
    

    再次解决。

    在我遇到的这种情况下,通过这两行代码解决了“远程服务器返回错误: (403) 已禁止。”的问题。

    其实还有个问题,返回内容乱码时,可能是Encoding或网站使用了gzip进行压缩,而HttpResponse默认不处理。以下代码尝试解决。

    HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
    Stream respStream = httpResp.GetResponseStream();
    StreamReader respStreamReader = new StreamReader(new GZipStream(respStream, CompressionMode.Decompress), System.Text.Encoding.UTF8);
    
  • 相关阅读:
    【经典数据结构】B树与B+树
    【经典算法】线性时间排序
    【经典算法】归并排序
    【经典算法】快速排序
    python模块之shelve
    python模块之pickle
    python模块之json
    python之序列化
    python模块之shutil和zipfile
    python模块之sys
  • 原文地址:https://www.cnblogs.com/LukeSteven/p/14777660.html
Copyright © 2011-2022 走看看