OAuth调用请求令牌会产生400错误

时间:2015-05-18 08:21:52

标签: oauth-2.0 linkedin-j

我想使用刚刚获得的授权码为我的应用程序获取访问令牌。我正在使用此代码

DefaultHttpClient client = new DefaultHttpClient();
URI uri = new URIBuilder().setScheme("https")
        .setHost("www.linkedin.com")
        .setPath("/uas/oauth2/accessToken")
        .setParameter("grant_type", "authorization_code")
        .setParameter("code", code)
        .setParameter("redirect_uri", "http://localhost:9090/ConnectSocialMedia/callBack.jsp")
        .setParameter("client_id", CONSUMER_KEY_OPTION)
        .setParameter("client_secret", CONSUMER_SECRET_OPTION)
        .build();
HttpPost post = new HttpPost(uri);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse response2 = client.execute(post);
System.out.println("Final Response------------>"+response2);

但我收到 HTTP / 1.1 400错误请求。我做错了什么?

任何帮助都会非常感激!

1 个答案:

答案 0 :(得分:1)

您将参数添加到令牌端点作为URL中的查询参数,但它们应该在POST参数中传递。你应该使用类似的东西:

DefaultHttpClient client = new DefaultHttpClient();
URI uri = new URIBuilder().setScheme("https")
    .setHost("www.linkedin.com")
    .setPath("/uas/oauth2/accessToken")
    .build();

List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("grant_type", "authorization_code"));
nvps.add(new BasicNameValuePair("code", code));
nvps.add(new BasicNameValuePair("redirect_uri", "http://localhost:9090/ConnectSocialMedia/callBack.jsp"));
nvps.add(new BasicNameValuePair("client_id", CONSUMER_KEY_OPTION));
nvps.add(new BasicNameValuePair("client_secret", CONSUMER_SECRET_OPTION));

HttpPost post = new HttpPost(uri);
post.setEntity(new UrlEncodedFormEntity(nvps));
HttpResponse response2 = client.execute(post);
System.out.println("Final Response------------>"+response2);