Last active
May 13, 2018 04:43
-
-
Save chathurangat/fe02a24f4e8e918f257cf4401819c793 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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