The exchange() method
Execute the HTTP method to the given URI template, writing the given HttpEntity to the request, and returns the response as ResponseEntity.
In below, i am going to show you some sample RestClient exchange requests with GET and POST HTTP methods.
GET request with No Request Parameters (With Headers)
In here the HTTP GET request is made without any query params (request params) and Basic Authentication header. Therefore by observing the below example, you can get an idea of how exchange method is used to send HTTP GET request without request parameters and headers.
public void findUserById() | |
{ | |
String username = "chathuranga"; | |
String password = "123"; | |
Integer userId = 1; | |
String url = "http://localhost:8080/users/" + userId; | |
//setting up the HTTP Basic Authentication header value | |
String authorizationHeader = "Basic " + DatatypeConverter.printBase64Binary((username + ":" + password).getBytes()); | |
HttpHeaders requestHeaders = new HttpHeaders(); | |
//set up HTTP Basic Authentication Header | |
requestHeaders.add("Authorization", authorizationHeader); | |
requestHeaders.add("Accept", MediaType.APPLICATION_JSON_VALUE); | |
//request entity is created with request headers | |
HttpEntity<AddUserRequest> requestEntity = new HttpEntity<>(requestHeaders); | |
ResponseEntity<FindUserResponse> responseEntity = restTemplate.exchange( | |
url, | |
HttpMethod.GET, | |
requestEntity, | |
FindUserResponse.class | |
); | |
if (responseEntity.getStatusCode() == HttpStatus.OK) { | |
System.out.println("response received"); | |
System.out.println(responseEntity.getBody()); | |
} else { | |
System.out.println("error occurred"); | |
System.out.println(responseEntity.getStatusCode()); | |
} | |
} |
GET request with Request Parameters (Query Params) and Headers
In here, the HTTP GET request is made with query parameters (request parameters) and Basic Authentication header. Therefore by observing the below example, you can get an idea of how exchange method is used to send HTTP GET request with request params and headers.
The generated request URL will be something like below. You can see that it includes the query params.
http://localhost:53793/users/1?name=chathuranga&email=chathuranga.t@gmail.com
public void findUserById() | |
{ | |
String username = "chathuranga"; | |
String password = "123"; | |
Integer userId = 1; | |
String url = "http://localhost:" + port + "/users/" + userId; | |
//setting up the HTTP Basic Authentication header value | |
String authorizationHeader = "Basic " + DatatypeConverter.printBase64Binary((username + ":" + password).getBytes()); | |
HttpHeaders requestHeaders = new HttpHeaders(); | |
//set up HTTP Basic Authentication Header | |
requestHeaders.add("Authorization", authorizationHeader); | |
requestHeaders.add("Accept", MediaType.APPLICATION_JSON_VALUE); | |
//request entity is created with request headers | |
HttpEntity<AddUserRequest> requestEntity = new HttpEntity<>(requestHeaders); | |
//adding the query params to the URL | |
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(url) | |
.queryParam("name", "chathuranga") | |
.queryParam("email", "chathuranga.t@gmail.com"); | |
ResponseEntity<FindUserResponse> responseEntity = restTemplate.exchange( | |
uriBuilder.toUriString(), | |
HttpMethod.GET, | |
requestEntity, | |
FindUserResponse.class | |
); | |
if (responseEntity.getStatusCode() == HttpStatus.OK) { | |
System.out.println("response received"); | |
System.out.println(responseEntity.getBody()); | |
} else { | |
System.out.println("error occurred"); | |
System.out.println(responseEntity.getStatusCode()); | |
} | |
} |
POST request with Request Body and Headers
In here the HTTP POST request is made with valid request body and Basic Authentication header. Therefore by observing the below example, you can get an idea of how exchange method is used to send HTTP POST request with request body and headers.
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 "); | |
} | |
} |
Thanks. very helpful.
LikeLike
Have you ever considered creating an ebook or guest authoring on other blogs?
I have a blog centered on the same subjects you discuss and would really like to have you share some stories/information. I know my audience would value your work.
If you are even remotely interested, feel free to send me an e-mail.
LikeLike
I pay a quick visit everyday some websites and sites to read content, however this webpage presents quality based
posts.
LikeLike
What’s up to every body, it’s my first pay a visit of this webpage; this
website contains amazing and actually good stuff in support of readers.
LikeLike
I’m really enjoying the theme/design of your web site. Do you ever run into any internet browser compatibility problems?
A couple of my blog visitors have complained about
my blog not operating correctly in Explorer but looks great in Chrome.
Do you have any solutions to help fix this problem?
LikeLike
Superb blog! Do you have any suggestions for aspiring writers?
I’m planning to start my own website soon but I’m a little
lost on everything. Would you suggest starting with a free platform like WordPress or go
for a paid option? There are so many options out there that I’m totally overwhelmed ..
Any recommendations? Thanks a lot!
LikeLike