Skip to content

Instantly share code, notes, and snippets.

@chathurangat
Last active May 13, 2018 04:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chathurangat/fe02a24f4e8e918f257cf4401819c793 to your computer and use it in GitHub Desktop.
Save chathurangat/fe02a24f4e8e918f257cf4401819c793 to your computer and use it in GitHub Desktop.
public void httpPostRequestWithHeadersAndBody()
{
String url = "http://localhost:8080/users";
String username = "chathuranga";
String password = "123";
//set up the basic authentication header
String authorizationHeader = "Basic " + DatatypeConverter.printBase64Binary((username + ":" + password).getBytes());
//setting up the request headers
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
requestHeaders.add("Authorization", authorizationHeader);
//setting up the request body
User user = new User();
user.setName("Sample User");
user.setUsername("user1");
user.setPassword("pass123");
//request entity is created with request body and headers
HttpEntity<User> requestEntity = new HttpEntity<>(user, requestHeaders);
ResponseEntity<UserResponse> responseEntity = restTemplate.exchange(
url,
HttpMethod.POST,
requestEntity,
UserResponse.class
);
if(responseEntity.getStatusCode() == HttpStatus.OK){
UserResponse user = responseEntity.getBody();
System.out.println("user response retrieved ");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment