【问题标题】:Getting the remote server returned an error 403 forbidden exception获取远程服务器返回错误 403 禁止异常
【发布时间】:2015-10-16 07:42:02
【问题描述】:

我正在尝试从 WCF 服务访问 https://api.github.com/search/repositories?q=service+language:assembly%26sort=stars%26order=desc 并获得 the remote server returned an error (403) forbidden 异常。

我已经尝试添加 httprequest.UseDefaultCredentials = true;httprequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"; 但到目前为止,这些都没有帮助我。

下面是使用的代码:

HttpWebRequest httprequest = (HttpWebRequest)HttpWebRequest.Create("https://api.github.com/search/repositories?q=service+language:assembly%26sort=stars%26order=desc");
httprequest.Proxy = new WebProxy()
{
   Address = new Uri(Proxy_address),
   Credentials = System.Net.CredentialCache.DefaultNetworkCredentials
};
httprequest.UseDefaultCredentials = true;
httprequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
httprequest.KeepAlive = true;
HttpWebResponse GISTResponse = (HttpWebResponse)httprequest.GetResponse();

请帮忙。

【问题讨论】:

  • 这里的 Proxy_address 是什么?

标签: wcf http-status-code-403


【解决方案1】:

它可以是很多东西。 测试您的代码,我注意到您缺少 UserAgent 并且您的 Accept 是错误的,因为 git 的要求。

尝试删除 Accept 并添加这一行:

httprequest.UserAgent = "My request";

如果你仍然有问题,你可以自己检查发生了什么,添加一个 try 和这个 catch 块,并检查 git 中的响应文本:

catch (WebException exception)
            {
                string responseText;

                using (var reader = new StreamReader(exception.Response.GetResponseStream()))
                {
                    responseText = reader.ReadToEnd();
                }
            }

希望对你有帮助

【讨论】:

  • 我添加了 UserAgent,它运行良好。谢谢 :)。但是你能告诉我为什么需要 UserAgent 吗? UserAgent 是否存在任何默认值?
  • UserAgent 是可选的(w3.org/Protocols/HTTP/HTRQ_Headers.html#user-agent),但是 Git 需要它,它必须是他们的策略。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多