在尝试从使用OAUTH的服务下载数据时,我似乎遇到了HttpWebRequest的问题。我首先创建一个HttpWebRequest,然后将OAUTH信息放在Authorization标头中。但是,只要调用GetRequestStream()(由Wireshark验证),就会发送标头。该服务期望标头和正文是同一请求的一部分,而不是单独的请求。在调用GetResponse()之前,不应发送数据。如果您知道如何确保同时发送所有数据,请与我们联系。感谢。
private HttpWebRequest GetWebRequest(string requestURI_, string token_, string tokenSecret_, int contentLength_)
{
Uri requestURI = new Uri(requestURI_);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestURI);
request.ProtocolVersion = new Version("1.1");
request.Expect = null; //Turn off the "Expect" header
request.ServicePoint.Expect100Continue = false;
request.SendChunked = false;
request.ServicePoint.UseNagleAlgorithm = false;
string authHeader = "";
GetOAUTHHeader(out authHeader, requestURI, token_, tokenSecret_);
request.Headers.Add("Authorization", authHeader);
request.ContentType = "application/octet-stream";
request.UserAgent = "DotNet3.5";
request.Accept = "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2";
request.Method = "POST";
request.ContentLength = contentLength_;
return request;
}
private string GetWebResponse()
{
string requestBody = "This is the request body";
HttpWebRequest request = GetWebRequest(requestURI_, accessToken_, accessTokenSecret_, requestBody.Length);
Stream requestStream = request.GetRequestStream(); //For some reason, the headers are sent here
StreamWriter requestWriter = new StreamWriter(requestStream);
requestWriter.Write(requestBody);
requestWriter.Close();
requestStream.Close();
WebResponse response = request.GetResponse(); //The body of the request is sent here
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string responseInfo = responseReader.ReadToEnd();
responseReader.Close();
response.Close();
return responseInfo;
}