4

Hello I switched from RestTemplate to HttpClient from java 11. I want to switch from OAuth2RestTemplate to HttpClient from java 11 also.

I cannot find any materials about using HttpClient with OAuth2. Is it possible in easy way?

And is it good idea? Or should I use WebClient from spring?

lospejos
  • 1,976
  • 3
  • 19
  • 35

1 Answers1

7

I just did post using HttpClient to grab OAuthToken and then I added token to headers of next requests.

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);
    }