如果我正在为第三方Api的资源发出OAuth访问令牌请求,那么就可以获取所有客户案例数据。
此GET不需要查询字符串,因为我只是请求数据,但我的问题是,我是否还需要指定某种类型的请求流(字节数据),或者只是假设应该省略ContentLength并由Request对象读取为-1?
e.g。我不必担心设置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 :(得分:0)
除非您实际发布数据,否则您无需对请求流执行任何操作。根据您正在做的事情,您甚至可以使用WebClient及其DownloadString()方法,并避免使用较低级别的WebRequest等涉及的大量额外代码。
当然,你失去了一些控制力和灵活性,但如果它是一个简单的API,你可能不需要它。