Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;

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}]}

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.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
695 views
Welcome To Ask or Share your Answers For Others

1 Answer

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...