我正在尝试使用Java访问API并使用oauth2授权令牌。以下是客户端代码:
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://res-api");
post.setHeader("Content-Type","application/json");
post.setHeader("Authorization", "Bearer " + finalToken);
JSONObject json = new JSONObject();
// json.put ...
// Send it as request body in the post request
StringEntity params = new StringEntity(json.toString());
post.setEntity(params);
HttpResponse response = httpclient.execute(post);
httpclient.getConnectionManager().shutdown();
这将返回401错误。
使用相同的令牌,等效的curl命令没有任何问题:
curl -H "Content-Type:application/json" -H "Authorization:Bearer randomToken" -X POST -d @example.json http://rest-api
我尝试注销该请求,并且看起来授权设置正确
DEBUG [2016-06-28 20:51:13,655] org.apache.http.headers: >> Authorization: Bearer authRandomToKen; Path=/; Domain=oauth2-server; Expires=Wed, 29 Jun 2016 20:51:13 UTC
我通过复制粘贴相同的令牌尝试了curl命令,它正常工作。
虽然我也看到了这行字
DEBUG [2016-06-28 20:51:13,658] org.apache.http.impl.client.DefaultHttpClient: Response contains no authentication challenges
Boomerang
来测试。我每天在工作中都是使用它来解决完全相同的问题。 - Dom