【发布时间】:2018-12-04 12:57:45
【问题描述】:
我正在尝试使用 http 客户端获取 oauth 令牌,但它会导致 HTTP/1.1 401 未授权错误。 我最初尝试如下使用 curl 请求,并且成功。 (出于安全考虑,此处未显示原始参数值)
curl --request POST --url oauthtokenHttpsurl --header 'content-type: application/json' --data '{"client_id":"clientId","client_secret":"client_secret","audience":"audienceurl","grant_type":"credentials"}'
然后我尝试使用 apache httpclient 在 java 中实现相同的功能,但它给出了 401 Unauthorized 错误
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
public class TestOAuthPost {
public static void main(String[] args) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost httppost = new HttpPost("oauthtokenHttpsurl");
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty("grant_type", "credentials");
jsonObj.addProperty("audience", "audienceurl");
jsonObj.addProperty("client_id", "client_id");
jsonObj.addProperty("client_secret", "client_secret");
StringEntity se = new StringEntity(jsonObj.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
// Execute HTTP Post Request
HttpResponse response = httpClient.execute(httppost);
String result = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
// 401 Unauthorized error
} catch (IOException e) {
System.out.println("erss");
}
}
}
我是第一次使用 httpclient 库和 oauth。
有人可以指导一下吗。
【问题讨论】:
-
这是我的错误。它正在工作。客户端 ID 中存在复制轻微拼写错误
标签: java oauth-2.0 apache-httpclient-4.x