2012-03-04 66 views
0

如果我爲我封裝的第三方Api的資源進行OAuth訪問令牌請求,以獲取所有客戶案例數據。你需要一個無參數GET的緩衝區嗎?

這個GET沒有querystrings所需,因爲我只是請求數據回來,但我的問題是,我仍然需要指定某種請求流(字節數據),或者只是假設ContentLength應該留下out並被Request對象讀爲-1?

例如我不必擔心設置ContentLength或緩衝區的做法。我只需要使用流讀取器來獲取返回的.json或API發回給我的正確內容?

 HttpWebResponse response; 
     Stream dataStream; // data returned from the response 
     byte[] buffer = null; // data to send in the request body 

     // FYI the "data" variable is just an incoming param to my send method, a string if I want to send data in the request (i.e. json, xml, whatever I am sending if needed) 
     if (!string.IsNullOrEmpty(data.Trim())) buffer = Encoding.UTF8.GetBytes(data); 

     // the resourceUrl variable I'm specifying for example is "ttp://someThirdPartyApi.com/api/v1/cases.json" 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resourceUrl); 

     // I then add an authorization header to the resonse.Headers (not shown here) 

     request.ServicePoint.Expect100Continue = false; 
     request.PreAuthenticate = true; 

     // do we have any data to send in the request -body-?? 
     if (buffer != null && buffer.Any()) 
     { 
      request.ContentLength = buffer.Length; 

      using (Stream stream = request.GetRequestStream()) 
      { 
       stream.Write(buffer, 0, buffer.Length); 
       stream.Close(); 
      } 
     } 

     // no data to send, just get the data returned in the response using a StreamReader 
+0

你試過了嗎?發生了什麼? – Oded 2012-03-04 09:00:45

回答

0

除非您實際發佈數據,否則您無需對請求流進行任何操作。根據你在做什麼,你甚至可以使用WebClient及其DownloadString()方法,並避免使用較低級WebRequest等涉及的大量額外代碼。

當然,你失去了一些控制和靈活性,但如果它是一個簡單的API,也許你不需要。

+0

是的我試圖遠離WebClient只是因爲我永遠不知道我們可能會把它移到什麼環境。我不介意額外的開銷,我可以創建幫助程序或實用程序方法來清理並重用。 – PositiveGuy 2012-03-04 09:11:24

+0

你是什麼意思?你在談論遷移到Mono嗎? Mono支持WebClient。根據你所處的環境,你沒有理由不能使用其中一種 - 這就是你想要的控制級別,就這些。 – Jordan 2012-03-04 09:13:45

+0

是的,沒有理由不去完全控制,以防您需要它。爲什麼設計一些有限的東西,當你不知道以後是否會受到這些限制的打擊。總是要設計靈活性,在這種情況下,使用HttpWebRequest或使用流獲取數據的代碼只需幾行代碼就足夠了......編寫更多代碼行來編寫代碼並不是什麼大事我的應用程序從長遠來看可以擴展,所以我們不必必須回頭重構這個。 – PositiveGuy 2012-03-04 09:29:23