I am aware of the similar posts and i checked them, but non of them could help me.
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:
{
"title": "foo",
"description": "bar",
"completed": "false"
}
and set the basic auth (with username and password). The API sends a response like this:
{
"id": 0001
}
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.
Task task = new Task("foo", "bar", false);
RestTemplate template = new RestTemplate();
HttpEntity<Task> httpEntity = new HttpEntity<>(task, createHttpHeader());
ResponseEntity<TaskResponse> 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);
}
I discovered, that this implementation is fine. It accepts String as a Response type. There was another problem, but not related to this context.