2013-02-17 32 views
2

出於某種原因,我在嘗試從我正在使用的Web API獲取JSON結果時,在Visual Studio中收到403:Forbidden異常。當我在我的網絡瀏覽器中嘗試使用網絡API網址時,所有內容都應該顯示。有任何想法嗎?HTTPClient返回HttpRequestException WinRT

的主要代碼:

 theURI = "http://isitup.org/duckduckgo.com.json"; 
     HttpClient httpClient = new HttpClient(); 
     httpClient.MaxResponseContentBufferSize = Int32.MaxValue; 
     var jsonResponse = await httpClient.GetStringAsync(theURI); 

     var rootObject = JsonConvert.DeserializeObject<StatusMessage.RootObject>(jsonResponse); 
     int statuscode = rootObject.status_code; 

     if (statuscode == 1) 
     { 
      txtStatus.Text = "Website is UP!"; 
     } 
     else if (statuscode == 2) 
     { 
      txtStatus.Text = "Website is DOWN!"; 
     } 
     else 
     { 
      txtStatus.Text = "Invalid domain!"; 
     } 

和類文件

class StatusMessage 
{ 
    public class RootObject 
    { 
     public string domain { get; set; } 
     public int port { get; set; } 
     public int status_code { get; set; } 
     public object response_ip { get; set; } 
     public object response_code { get; set; } 
     public object response_time { get; set; } 
    } 

} 
+0

那麼想必你的瀏覽器發送某種身份驗證... – 2013-02-17 20:23:28

+0

@JonSkeet是的,想過,但我想不通的地方,這將是。 – AndreasB 2013-02-17 20:26:13

+0

那麼使用Wireshark或類似的東西來查看你的瀏覽器正在發送什麼。 – 2013-02-17 20:50:52

回答

2

好像服務器,如果您使用的是默認的用戶代理響應你403。如果您將其更改爲chrome用戶代理,則服務器應答正常。

var url = new Uri("http://isitup.org/duckduckgo.com.json"); 
var req = new HttpClient(); 
var message = new HttpRequestMessage(HttpMethod.Get, url); 
message.Headers.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17"); 
var response = await req.SendAsync(message); 
var responseString = await response.Content.ReadAsStringAsync(); 
+0

工作就像它應該!謝謝Teemu – AndreasB 2013-02-18 08:30:57

+0

嘗試使用bing地圖位置api時會遇到此問題。謝謝! – 2016-04-27 14:22:24

相關問題