2015-10-16 133 views
0

我试图从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";但这些都没有帮助到目前为止。以下是使用的代码。获取远程服务器返回的错误403禁止的异常

`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();` 

请大家帮忙。

+0

是什么Proxy_address这里? – Shetty

回答

0

它可以是很多事情。 测试你的代码,我可能会注意到你错过了UserAgent和你的接受是错误的,由于git的要求。

尝试删除接受并加入这一行:

httprequest.UserAgent = "My request"; 

如果您仍然有问题,你可以自己检查所发生的事情添加一个尝试,这个catch块,并从混帐检查reponseText :

catch (WebException exception) 
      { 
       string responseText; 

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

希望它有助于

+0

我加了UserAgent,它工作正常。谢谢 :)。但是,你能告诉我为什么需要UserAgent吗? UserAgent是否有默认值? – mailmehere

+0

UserAgent是可选的(http://www.w3.org/Protocols/HTTP/HTRQ_Headers.html#user-agent),但它是Git所必需的,它必须是它们的策略。 –

相关问题