title: RestTemplate POST - handle response
body: <p>I am aware of the similar posts and i checked them, but non of them could help me.</p>
  
  <p>I want to POST to a API (that manages for examples tasks) that requires three parameters and a basic auth.
  In postman it works. I provide the body like:</p>
  
  <pre><code>{
      "title": "foo",
      "description": "bar",
      "completed": "false"
  }
  </code></pre>
  
  <p>and set the basic auth (with username and password). The API sends a response like this:</p>
  
  <pre><code>{
    "id": 0001
  }
  </code></pre>
  
  <p>Everything works fine if i send a POST to the api, but now i want to implement it in java. I am getting a 400 bad request if i try to send a POST: HttpClientErrorException: 400 Bad Request (DefaultResponseErrorHandler). The Task and TaskResponse are pojo's with the fields like in the request and response and a no-arg/full-arg constructor, getter and setter.</p>
  
  <pre><code> Task task = new Task("foo", "bar", false);
          RestTemplate template = new RestTemplate();
          HttpEntity&lt;Task&gt; httpEntity = new HttpEntity&lt;&gt;(task, createHttpHeader());
          ResponseEntity&lt;TaskResponse&gt; result = template.exchange(uri, HttpMethod.POST, httpEntity, TaskResponse.class);
  
  private HttpHeaders createHttpHeader() {
          HttpHeaders requestHeaders = new HttpHeaders();
          requestHeaders.setContentType(MediaType.APPLICATION_JSON);
          requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
          requestHeaders.set("Authorization", createBasicAuthHeaderValue(username, password));
          return requestHeaders;
      }
  
      private String createBasicAuthHeaderValue(String username, String password) {
          String credentials = username + ":" + password;
          byte[] base64Credentials = Base64.encodeBase64(credentials.getBytes());
          return "Basic " + Arrays.toString(base64Credentials);
      }
  </code></pre>