2012-03-04 62 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