0

Box.com 的企业用户配置 API 需要在请求的标头中使用 OAUTH2 令牌(“授权:承载 faKE_toKEN_1234”)。我已经针对http://www.xhaus.com/headershttp://httpbin.org/posthttp://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;
4

1 回答 1

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();
}
于 2015-03-09T17:23:34.827 回答