如何强制 WebRequest 在 POST 期间发送 Authorization 标头 [英] How to force WebRequest to send Authorization header during POST

查看:46
本文介绍了如何强制 WebRequest 在 POST 期间发送 Authorization 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 WebRequest 发送 POST 时,即使我手动设置了标头并将 PreAuthenticate 设置为 true,授权标头也不会与请求一起发送,例如:

When using WebRequest to send a POST, the Authorization header is not sent with the request even though I have manually set the header and set PreAuthenticate to true, eg:

webRequest.Headers["Authorization"] = "OAuth oauth_consumer_key=bFPD...";
webRequest.PreAuthenticate = true;

使用 Fiddler 我可以看到 Authorization 标头没有发送.目标站点 (Twitter) 返回 400(错误请求)而不是 401(未授权),因此这是 WebRequest 发送授权数据所需的错误质询.供参考,返回的内容为:

Using Fiddler I can see that the Authorization header is not sent. The target site (Twitter) returns a 400 (Bad request) rather than a 401 (Not authorized) which is therefore the incorrect challenge required for WebRequest to send the Authorization data. For information, the returned content is:

{"errors":[{"message":"Bad Authentication data","code":215}]}

那么,我该如何解决这个问题?如何强制 WebRequest 发送带有初始请求的授权?请注意,授权数据不是基本身份验证,而是一个 OAuth 字符串.

So, how do I get around this? How can I force WebRequest to send the Authorization with initial request? Note that the authorization data is not Basic Authentication, rather it is an OAuth string.

谢谢

推荐答案

这是我的解决方案.该值在变量 json 中.

Here's my solution. The value is in variable json.

var myUri = new Uri(fullpath);
var myWebRequest = WebRequest.Create(myUri);
var myHttpWebRequest = (HttpWebRequest)myWebRequest;
myHttpWebRequest.PreAuthenticate = true;
myHttpWebRequest.Headers.Add("Authorization", "Bearer " + AccessToken);
myHttpWebRequest.Accept = "application/json";

var myWebResponse = myWebRequest.GetResponse();
var responseStream = myWebResponse.GetResponseStream();
if (responseStream == null) return null;

var myStreamReader = new StreamReader(responseStream, Encoding.Default);
var json = myStreamReader.ReadToEnd();

responseStream.Close();
myWebResponse.Close();

这篇关于如何强制 WebRequest 在 POST 期间发送 Authorization 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆