有没有办法将java.net.http.HttpClient与Oauth2一起使用?

有没有办法将java.net.http.HttpClient与Oauth2一起使用?,java,oauth-2.0,httpclient,java-http-client,Java,Oauth 2.0,Httpclient,Java Http Client,您好,我从java 11从RestTemplate切换到HttpClient。我还想从java 11从OAuth2RestTemplate切换到HttpClient 我找不到任何关于将HttpClient与OAuth2一起使用的资料。有可能吗 这是个好主意吗?或者我应该使用spring中的WebClient吗?我刚刚使用HttpClient发布了一篇博文来获取OAuthToken,然后我将token添加到下一个请求的头中 String tokenRequest = "client

您好,我从java 11从
RestTemplate
切换到
HttpClient
。我还想从java 11从
OAuth2RestTemplate
切换到
HttpClient

我找不到任何关于将
HttpClient
与OAuth2一起使用的资料。有可能吗


这是个好主意吗?或者我应该使用spring中的
WebClient
吗?

我刚刚使用
HttpClient
发布了一篇博文来获取OAuthToken,然后我将token添加到下一个请求的头中

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);
    }
字符串令牌请求=
“客户端id=”
+lmGatewayCorrectClientId
+“&client\u secret=”
+lmGatewayCorrectClientSecret
+“&授权类型=”
+lmGatewayCorrectGrantType;
HttpClient oAuth2Client=HttpClient.newBuilder().build();
HttpRequest oAuth2Request=
HttpRequest.newBuilder()
.header(内容\u类型、应用程序\u表单\u URL编码\u值)
.uri(uri.create(lmGatewayCorrectAccessTokenUri))
.POST(HttpRequest.bodypublisher.ofString(tokenRequest))
.build();
HttpResponse oAuth2Response=null;
试一试{
oAuth2Response=oAuth2Client.send(oAuth2Request,HttpResponse.BodyHandlers.ofString());
}捕获(例外e){
logger.error(e.getMessage(),e);
}

这对我来说很好。