2015-10-16 131 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所必需的,它必須是它們的策略。 –

相關問題