HttpClient 中的 Authorization Bearer token?
2022-09-01 09:40:19
我正在尝试使用Java中的oauth2授权令牌访问API 这是客户端代码
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命令,并且t工作正常
虽然我也看到这条线
DEBUG [2016-06-28 20:51:13,658] org.apache.http.impl.client.DefaultHttpClient: Response contains no authentication challenges