Box.com的企业用户配置API在请求的标头中需要OAUTH2令牌(“授权:承载faKE_toKEN_1234”)。我已针对http://www.xhaus.com/headers,http://httpbin.org/post和http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi运行了下面的代码,并使用 Microsoft网络监视器观察了数据包,据我所知,我的请求标头没有包括我希望包含在那里的“授权”价值。
下面的代码是否遗漏了某些内容(代码或点)?
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(API_URL);
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout=10000;
string postData = Parameters;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);
request.ContentLength = byte1.Length;
Stream reqStream = request.GetRequestStream();
reqStream.Write(byte1, 0, byte1.Length);
reqStream.Close();
//This is puzzling me, why can't I see this header anywere
//when debugging with packet monitor etc?
request.Headers.Add("Authorization: Bearer " + access_token);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
Stream dataStream = response.GetResponseStream ();
StreamReader reader = new StreamReader (dataStream);
string txtResponse = reader.ReadToEnd ();
return txtResponse;
答案 0 :(得分:1)
我认为您需要在 之前设置标题 ,然后编写postData并关闭请求流。这似乎对我有用:
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.xhaus.com/headers");
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
request.Headers.Add("Authorization: Bearer_faKE_toKEN_1234");
string postData = "postData";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
request.ContentLength = byte1.Length;
Stream reqStream = request.GetRequestStream();
reqStream.Write(byte1, 0, byte1.Length);
reqStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string txtResponse = reader.ReadToEnd();
Console.WriteLine(txtResponse);
Console.ReadKey();
}