2013-12-20 41 views
1

我正在使用api,如果URL無效,則返回錯誤400;如果每日qouta耗盡50%,則返回錯誤401。它也返回json,但是我無法下載這個json,因爲發生這些錯誤時發生異常。現在用的API是 http://www.sharedcount.com/documentation.php如何處理http 400和401錯誤,同時使用webclient下載JSON

的代碼我用寫的是... ...

private void _download_serialized_json_data(Uri Url) 
     { 
      var webClient = new WebClient(); 
       var json_data = string.Empty; 
       // attempt to download JSON data as a string 
       try 
       { 
        webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted); 
        webClient.DownloadStringAsync(Url); 
       } 
       catch (Exception) { } 

     } 

void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
     { 
      String Json = null;  

      try 
      { 
       Json = e.Result; 
      } 
      catch (Exception ex) 
      { 

      } 

      if(Json!=null) 
      { 
       data=JsonConvert.DeserializeObject<RootObject>(Json); 
       result.Text = "facebook : "+data.Facebook.like_count+"\nGooglePlus : "+data.GooglePlusOne; 
      } 
      else 
      { 
       result.Text = "Invald URL \nor you exceeded your daily quota of 100,000 queries by 50%."; 

      } 

     } 

目前正在顯示,如果出現異常,這兩個錯誤。但我想下載json並顯示它。我應該怎麼做,

回答

1

獲得響應的內容,你將需要使用System.Net.Http.HttpClient代替。從這裏安裝:Microsoft HTTP Client Libraries

那就試試這個:

private async void Foo2() 
{ 
    Uri uri = new Uri("http://localhost/fooooo"); 
    HttpClient httpClient = new HttpClient(); 
    HttpResponseMessage response = await httpClient.GetAsync(uri); 
    HttpStatusCode statusCode = response.StatusCode; // E.g.: 404 
    string reason = response.ReasonPhrase; // E.g.: Not Found 
    string jsonString = await response.Content.ReadAsStringAsync(); // The response content. 
} 
0

你可以嘗試這樣的事情,

void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
    { 
     String Json = null;  

     if(e.Error != null) 
     { 
      //Some error occured, show the error message 
      var ErrorMsg = e.Error.Message; 
     } 
     else 
     { 
      //Got some response .. rest of your code 
      Json = e.Result; 
     } 

    } 
+0

其實我不想知道它是錯誤400還是401,或者我想讀取json,不管錯誤響應是什麼。 – Rishabh876

0

我使用Web客戶端遇到了同樣的問題,我看到的錯誤響應流中的提琴手被抓獲,但我的.NET代碼被捕捉異常並且似乎沒有捕獲響應流。

您可以從WebException對象讀取Response流以獲取響應數據流。

using (System.Net.WebClient client = new System.Net.WebClient()) 
{ 
    string response = ""; 
    try 
    { 
     response = client.UploadString(someURL, "user=billy&pass=12345"); 
    } 
    catch(WebException ex) 
    { 
     using (System.IO.StreamReader sr = new System.IO.StreamReader(ex.Response.GetResponseStream())) 
     { 
      string exResponse = sr.ReadToEnd(); 
      Console.WriteLine(exResponse); 
     } 
    } 
}