title: Unreliable response from java.net.http.HttpClient call using Java 11 and Spring Boot
body: <p>I'm writing a back-end application in Spring Boot that calls another API from a third party.</p>
  <p>I'm having a problem with this particular call, which retrieves a token object containing a bearer token, which then I use in their other endpoints.
  The retrieved token sometimes works, most of the time it doesn't, when calling the other endpoints, resulting in an unauthorized response.</p>
  <pre><code>@RestController
  public class CotizacionController {
  
      Logger logger = LoggerFactory.getLogger(CotizacionController.class);
  
      @Value(&quot;${service.credentials.tokenServer}&quot;)
      private String tokenServer;
  
      @Value(&quot;${service.credentials.grantType}&quot;)
      private String grantType;
  
      @Value(&quot;${service.credentials.username}&quot;)
      private String username;
  
      @Value(&quot;${service.credentials.password}&quot;)
      private String password;
  
      HttpClient client = HttpClient.newHttpClient();
  
      @RequestMapping(&quot;/create&quot;)
      public Object Create() throws IOException, InterruptedException {
  
          HashMap&lt;String, String&gt; parameters = new HashMap&lt;&gt;();
          parameters.put(&quot;grant_type&quot;, grantType);
          parameters.put(&quot;username&quot;, username);
          parameters.put(&quot;password&quot;, password);
  
          String form = parameters.keySet().stream()
                  .map(key -&gt; key + &quot;=&quot; 
                                  + URLEncoder.encode(parameters.get(key), 
                                                      StandardCharsets.UTF_8))
                  .collect(Collectors.joining(&quot;&amp;&quot;));
  
          HttpRequest request = HttpRequest.newBuilder()
                  .uri(URI.create(tokenServer))
                  .header(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;)
                  .POST(BodyPublishers.ofString(form)).build();
  
          HttpResponse&lt;?&gt; response = client.send(request, BodyHandlers.ofString());
  
          TokenResponse result = new ObjectMapper().readValue(response
                                     .body().toString(), TokenResponse.class);
  
          return result;
      }
  
  }
  </code></pre>
  <p>And here's an example token object:</p>
  <pre><code>{
      &quot;access_token&quot;: &quot;z-bu-Pde6M2dlPiaRzd5XpTrT7ohpFQZe157HHVLfdKJWsdmKCloK7AYGEw7SLCe28tjYAxo8MZOE_3W00HEa-bqgUvcrAKfxIubAq0UGXv7jLPWbRwWzhAUCDon3kdstUrJ_OKRN2y26W6qyDBGDqlP5NRSF4unH_pD_ShmpDlSxZdYUqD0da5Y2_uO6YRs5GuWA7XhI9sPa98SxuXN_dwiDJVif418xK646fUgWR8&quot;,
      &quot;token_type&quot;: &quot;bearer&quot;,
      &quot;expires_in&quot;: &quot;3599&quot;
  }
  </code></pre>
  <p>Retrieving tokens using <strong>postman works perfectly fine</strong>, so it couldn't be an issue from the third party API. I also have this <strong>same service implemented in .NET Core 3 and it also works perfectly fine</strong> over there.</p>
  <p>What confuses me the most is that the actual HttpClient call works, I do get a correct Json which is mapped to my TokenResponse object just fine. It's just that the token value is invalid... sometimes.</p>
  <p>I've also tried using RestTemplate and WebClient Spring libraries, but the results are the same. Call works, but retrieved token is invalid.</p>
  <p>At first I thought I was having a race condition, since initially I had another HttpClient in there with another endpoint using the response from the token call. So I simplified it into only the token call and manually copying the token value into postman requests. Didn't work.</p>
  <p>Then I thought maybe my HttpClient authorization header was malformed, but that's disproven since simply copying the token into a protected endpoint using a postman request shows that the token doesn't work.</p>
  <p>And other things I've tried:</p>
  <ul>
  <li>Pasting the form string I generate in the controller into the Postman request to make sure it's valid.</li>
  <li>Check that the URLEncoder is not messing up any form values.</li>
  <li>Copy the token value from the token object to use in another endpoint with Postman.</li>
  <li>Skip object mapping and return a simple String, and manually copying the token value from the response in Postman so I can then use it in another endpoint.</li>
  </ul>
  <p>I'm pretty lost at this point, only thing that comes to mind is that maybe the HttpClient.send() method might be parsing the body in a way that might be affecting the content? I doubt it, but I don't see what else could be happening.</p>