Take the 2-minute tour ×
Stack Apps is a question and answer site for apps, scripts, and development with the Stack Exchange API. It's 100% free, no registration required.

On the last stage of authentication against StackOverflow, I keep getting "400 Bad Request" code. It's supposed to be a simple POST request to https://stackexchange.com/oauth/access_token with a few parameters. What am i missing? Is it possible to get more info from the server about the problem ?

Any help will be much appreciated!

This is the code I use to send the request:

string code = HttpContext.Current.Request["code"];

// this is what we are sending
string post_data = "client_id={0}&client_secret={1}&code={2}&redirect_uri={3}";
post_data = string.Format(post_data, code, clientId, redirect_url, apiSecret);
post_data = HttpUtility.UrlEncode(post_data);

// this is where we will send it
string uri = "https://stackexchange.com/oauth/access_token";

// create a request
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";

// turn our request string into a byte stream
byte[] postBytes = Encoding.ASCII.GetBytes(post_data);

// this is important - make sure you specify type this way
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
Stream requestStream = request.GetRequestStream();

// now send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
share|improve this question

migrated from stackoverflow.com Jul 22 '12 at 7:29

This question came from our site for professional and enthusiast programmers.

    
Remove the urlencode and try. Maybe you are encoding it twice. –  DarkXphenomenon Jul 22 '12 at 6:50
    
How do you get the JSON containing OAuth access token fron the response using this method? –  Robin French Oct 25 '12 at 9:53
add comment

2 Answers 2

string post_data = "client_id={0}&client_secret={1}&code={2}&redirect_uri={3}";
post_data = string.Format(post_data, code, clientId, redirect_url, apiSecret);

Shouldn't that be

string post_data = "client_id={0}&client_secret={1}&code={2}&redirect_uri={3}";
post_data = string.Format(post_data, clientId, apiSecret, code, redirect_url);
share|improve this answer
add comment

Try removing the urlencode, you might be encoding it twice.

share|improve this answer
add comment

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .