获取远程服务器返回错误403禁止异常

时间:2015-10-16 07:42:03

标签: wcf

我尝试从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();`

请帮忙。

1 个答案:

答案 0 :(得分:0)

这可能是很多事情。 测试您的代码时,由于 git 的要求,我发现您缺少 UserAgent 并且接受是错误的。

尝试删除接受并添加以下行:

httprequest.UserAgent = "My request";

如果您仍有问题,可以自己检查添加try和此catch块的情况,并检查 git 中的reponseText:

catch (WebException exception)
            {
                string responseText;

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

希望有所帮助