开发者

Getting '(400) Bad Request' with GetResponseStream() in C#

I am using the following code to send a get request to facebook graph api oauth server.

public string GetAccessToken(string code)
    {
        HttpWebRequest req = (HttpWebRequest) WebRequest.Create(@"https://graph.facebook.com/oauth/access_token?client_id=249725835046216&redirect_uri=http://localhost:2794/&client_secret=APP_SECRETa&code=" + code);
        HttpWebResponse res = (HttpWebResponse)req.GetResponse();
        string response=res.GetResponseStream().ToString();
        return response;
    }

The above 开发者_StackOverflowcode throws the following exception:

The remote server returned an error: (400) Bad Request.

Meanwhile if I type the same url in browser, it works. Please help, where am I wrong?

(P.S In the URL, I am surely replacing APP_SECRET with the secret key)


Your querystring parameters should be UrlEncoded:

HttpWebRequest req = (HttpWebRequest) WebRequest.Create(@"https://graph.facebook.com/oauth/access_token?client_id=249725835046216&redirect_uri=" + UrlEncode("http://localhost:2794/") + "&client_secret=" + UrlEncode(APP_SECRET) + "&code=" + UrlEncode(code));


You have to encode the parameters of your URL. You could use the HttpUtility class for encoding your parameters.


Most probably you need to specify user agent to satisfy some check logic of a server:

HttpWebRequest req = (HttpWebRequest) WebRequest.Create(@"https://...&code=" + code);
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

try this and see if it helps.


The redirect URL needs to be the same as the one that you posten when getting a code.

Please check this article, helped me!
http://www.ronaldwidha.net/2011/03/24/facebook-oauth-access_token-return-http-400-error-validating-verification-code/


This is what happened to me and how to solve that:

  1. Redirect the user to

    https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL

  2. After user click allow, it'll hit our Redirect Uri

  3. At that point we'll get the code and we need to do a server side HTTP Get to the following Url to exchange the code with our oAuth access token:

    https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&client_secret=YOUR_APP_SECRET&code=THE_CODE_FROM_ABOVE

Now at step 3, I kept on getting Http 400 response back.

So after some research, I found out that on that redirect_uri that we submitted on step 3 doesn't do anything but validate the request. Thus, the value need to match with step 2.

In short :

redirect_uri MUST MATCH both step 2 and step 3

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜