【问题标题】:Is there a way to use java.net.http.HttpClient with Oauth2?有没有办法将 java.net.http.HttpClient 与 Oauth2 一起使用?
【发布时间】:2020-02-22 05:15:14
【问题描述】:
您好,我从 java 11 从 RestTemplate 切换到 HttpClient。我也想从 java 11 从 OAuth2RestTemplate 切换到 HttpClient。
我找不到任何有关将HttpClient 与 OAuth2 结合使用的资料。有没有简单的方法?
这是个好主意吗?还是我应该使用 spring 中的WebClient?
【问题讨论】:
标签:
java
oauth-2.0
httpclient
java-http-client
【解决方案1】:
我刚刚使用HttpClient 发布了 OAuthToken,然后我将令牌添加到下一个请求的标头中。
String tokenRequest =
"client_id="
+ lmGatewayCorrectClientId
+ "&client_secret="
+ lmGatewayCorrectClientSecret
+ "&grant_type="
+ lmGatewayCorrectGrantType;
HttpClient oAuth2Client = HttpClient.newBuilder().build();
HttpRequest oAuth2Request =
HttpRequest.newBuilder()
.header(CONTENT_TYPE, APPLICATION_FORM_URLENCODED_VALUE)
.uri(URI.create(lmGatewayCorrectAccessTokenUri))
.POST(HttpRequest.BodyPublishers.ofString(tokenRequest))
.build();
HttpResponse<String> oAuth2Response = null;
try {
oAuth2Response = oAuth2Client.send(oAuth2Request, HttpResponse.BodyHandlers.ofString());
} catch (Exception e) {
logger.error(e.getMessage(), e);
}