Hello Java programmers, if you have been using Spring for REST API development, both creation and consumption then you know that RestTemplate is one of the most commonly used tools for REST service invocations. So one of the major problems you might have in this RestTemplate is that how to set an "Accept" header on Spring RestTemplate request. In the last article, I have shown you how to POST and Consume JSON using RestTemplate in a Spring Based Java application and In this tutorial, we will go through some important points on how to add headers to RestTemplate and fix the errors related to them.
How to sett HTTP headers using Spring RestTemplate?
So let's have a look at RestTemplate GET request with parameters and headers.
//rest api url
String url = "XXX rest api url";
//RestTemplate instance creation
RestTemplate restTemplate = new RestTemplate();
//GET request
String json = restTemplate.getForObject(url, String.class);
//print the json response
System.out.println(json);
//query parameters appended to the URL
String url = "https://google.com/search?q=java";
// or else you can use placeholders to the URL for query parameters.
String url = "https://google.com/search?q={q}";
//RestTemplate instance creation
RestTemplate restTemplate = new RestTemplate();
//GET request
String jsonString = restTemplate.getForObject(url, String.class);
//print the json response
System.out.println(jsonString);
GET Request with parameters and headers.
In order to add custom request headers to HTTP request, you should use the generic exchange() method provided by the RestTemplate class. So let's have a method in there.
We propose using one of the exchange methods that accept HttpEntity and allow us to set HttpHeaders in this case (for example, Authorization, Accept, Content-Type, etc.).We can also set the HTTP method we want to utilize by utilizing one of the exchange methods.RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<String> httpEntity = new HttpEntity<>("some body", headers);
restTemplate.exchange(url, HttpMethod.PUT, httpEntity, String.class);In the above code segment, instead of setting headers by using dedicated methods, you can use the general set method.
headers.set("Accept", "application/json");It's also possible to provide HttpEntity to method postForObject() as a request parameter, as seen in the following example.
HttpEntity<String> entity = new HttpEntity<>("some body", headers);
restTemplate.postForObject(url, entity, String.class);
Let's have an another example with how to make a custom request headers to HTTP GET request, you can use the generic exchange() method provided by the RestTemplate class.
//query parameters appended to the URL
String url = "https://google.com/search?q=java";
// or else you can use placeholders to the URL for query parameters.
String url = "https://google.com/search?q={q}";
//RestTemplate instance creation
RestTemplate restTemplate = new RestTemplate();
//http headers
HttpHeaders headers = new HttpHeaders();
// set `Content-Type` and `Accept` headers
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
// example of custom header
headers.set("X-Request-Source", "Desktop");
// build the request
HttpEntity request = new HttpEntity(headers);
// make an HTTP GET request with headers
ResponseEntity<String> response = restTemplate.exchange(
url,
HttpMethod.GET,
request,
String.class,
1
);
// check response
if (response.getStatusCode() == HttpStatus.OK) {
System.out.println("Request Successful.");
System.out.println(response.getBody());
} else {
System.out.println("Request Failed");
System.out.println(response.getStatusCode());
}So let's have a real world example of how to set an "Accept" header on Spring RestTemplate request. Here is the Spring request handling code.
@RequestMapping(
value= "/uom_matrix_save_or_edit",
method = RequestMethod.POST,
produces="application/json"
)
public @ResponseBody ModelMap uomMatrixSaveOrEdit(
ModelMap model,
@RequestParam("parentId") String parentId
){
model.addAttribute("attributeValues",parentId);
return model;
}and below is the Java REST client.public void post(){
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("parentId", "parentId");
String result = rest.postForObject( url, params, String.class) ;
System.out.println(result);
}This is working fine and get a JSON string from the server side.
But need to clarify how to specify the Accept: header (ex- application/json, application/xml,..) and request method (ex- GET, POST, ...) when using the RestTemplate?
To answer this question, you can use one of the exchange methods that accepts an HttpEntity for which you can also set the HttpHeaders.(You can also sepecify the HTTP method you want to use).
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<>("body", headers);
restTemplate.exchange(url, HttpMethod.POST, entity, String.class);You can pass the HttpEntity as a request argument to postForObject.
HttpEntity<String> entity = new HttpEntity<>("body", headers);
restTemplate.postForObject(url, entity, String.class);This method is mentioned in here.
The request parameter can be a HttpEntity in order to add additional HTTP headers to the requerst.
So in the above, we have discussed how to make GET request with non parameters and also with parameters and headers. The request parameter can be a HttpEntity in order to add additional HTTP request headers to the request.
So in this tutorial, we discussed how to set an "Accept" header on Spring RestTemplate request with many examples.
Hope you understand those and hope to see you in the next tutorial. Until then Bye.
Other Spring MVC articles and Tutorials you may like
- 15 Spring Data JPA Interview Questions with Answers
- How to use MyBatis with Spring Boot in Java?
- 5 Best Courses to learn Reactive Spring and WebFlux
- How to use @SpringBootTest annotation in Java
- 20+ Spring Boot Interview Questions with Answers
- What is ModelAttribute in Spring MVC?
- Spring Boot + React.js example for Java developers
- What is the use of DispatcherServlet in Spring MVC?
- How to fix No Spring Bean found of Type using @Autowired
- How to upload a file and json on Postman?
- 6 Best Courses to learn Spring Framework
- 25+ Spring Security Interview Questions with Answers
- How to log SQL in a Spring Boot application?
- How to use RequestBody and ResponseBody on Spring MVC?
- Spring Boot + Angular Example for Fullstack Developers
- My Favorite Spring Boot Courses for Java programmers
- How to enable Spring security in a Java web application?
1 comment :
Use WebClient instead of RestTemplate, and if you are in core Java, you can use HttpClient also
Post a Comment