Skip to content

Instantly share code, notes, and snippets.

@chathurangat

chathurangat/post.java

Last active May 13, 2018
Embed
What would you like to do?
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