2015-04-26 27 views
0

新的Dropbox API文檔是在400錯誤連接到Dropbox的API第2版:嘗試使用C#接收所有嘗試

https://blogs.dropbox.com/developers/2015/04/a-preview-of-the-new-dropbox-api-v2/

我試圖執行一個簡單的元數據呼叫,但我有很少成功。這裏是我使用的代碼:

private void go() 
    { 
     var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.dropbox.com/2-beta/files/get_metadata"); 
     httpWebRequest.ContentType = "text/json"; 
     httpWebRequest.Method = "POST"; 
     httpWebRequest.Headers.Add("Authorization: Bearer xxxxxxxxxxxxxxxxxxx"); 

     using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) 
     { 
      string json = "{\"path\": \"/avatar_501.png\"}"; 

      streamWriter.Write(json); 
      streamWriter.Flush(); 
      streamWriter.Close(); 
     } 

     var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 
     using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) 
     { 
      var result = streamReader.ReadToEnd(); 
      this.TextBox1.Text = result; 
     } 
    } 

任何幫助將大規模讚賞!

+1

400響應的內容是什麼?只是猜測,但你的Content-Type頭是'text/json'而不是'application/json'。我不確定這是否允許,但錯誤響應的主體可能會告訴你確切的問題。 – smarx

+0

我也會建議在使用API​​時使用Web請求工具([Fiddler](http://www.telerik.com/fiddler))。這真的簡化了測試。您始終可以首先嚐試手動發送請求,並且當您驗證它正在工作時,請在代碼中執行請求。 –

回答

2

如果您嘗試此代碼,您會看到400響應的正文,它告訴您text/json不是有效的Content-Type。我將您的代碼轉換爲控制檯應用程序,並且使用Newtonsoft.Json作爲JSON序列化。否則,你的代碼和我之間唯一的區別是增加了異常處理獲得的400

class Program 
{ 
    static void Main(string[] args) 
    { 
     var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.dropbox.com/2-beta/files/get_metadata"); 
     httpWebRequest.ContentType = "text/json"; 
     httpWebRequest.Method = "POST"; 
     httpWebRequest.Headers.Add("Authorization: Bearer <REDACTED>"); 

     using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) 
     { 
      streamWriter.Write(JsonConvert.SerializeObject(new { 
       path = "/avatar_501.png" 
      })); 
     } 

     HttpWebResponse response; 

     try 
     { 
      response = (HttpWebResponse)httpWebRequest.GetResponse(); 
     } 
     catch (WebException e) 
     { 
      response = (HttpWebResponse)e.Response; 
     } 

     Console.WriteLine("Status code: {0}", (int)response.StatusCode); 
     using (var streamReader = new StreamReader(response.GetResponseStream())) 
     { 
      Console.WriteLine(streamReader.ReadToEnd()); 
     } 

     Console.ReadLine(); 
    } 
} 

身體的輸出如下:

Status code: 400 
Error in call to API function "files/get_metadata": Bad HTTP "Content-Type" header: "text/json". Expecting one of "application/json", "application/json; charset=utf-8", "text/plain; charset=dropbox-cors-hack". 

改變Content-Typeapplication/json原因呼籲成功。

+0

這解決了它 - 同時,指向我Newtonsoft肯定會有很大的幫助。我對使用JSON相當陌生,而且我很確定我一直在努力。謝謝! –