If I’m making an OAuth Access Token request for resources of a third party Api I wraped, to get all customer cases data for example.
There are no querystrings required for this GET since I am just requesting data back, but my question is, do I still need to specify a request stream (byte data) of some sort or just assume that the ContentLength should be left out and is read as -1 by the Request object?
e.g. I don’t have to worry about setting the ContentLength or buffer do I. I just need to use a stream reader to grab the returned .json or whatever the API sends back to me correct?
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
Unless you’re actually posting data, you don’t need to do anything with the request stream. Depending on what you’re doing, you might even be able to use WebClient and its DownloadString() method, and avoid a lot of the extra code involved in using the lower-level WebRequest, etc.
Of course, you lose some control and flexibility, but maybe you don’t need that if it’s a simple API.