Monday, May 6, 2024

How to set an "Accept:" header on Spring RestTemplate request? Example Tutorial

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?

In this article, I will teach you how to set headers on HTTP request using Spring REST Template

So let's have a look at RestTemplate GET request with parameters and headers.

Simple GET request

Here we are using the getForObject() to make the GET request. Below is an example of using the getForObject() method to fetch the user information as a JSON string

//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);


Simple GET Request with request parameters.

If you want to pass query parameters, you can use the URL appended with them or else you can add placeholders to the URL for query parameters.

//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.

How to set an "Accept:" header on Spring RestTemplate request?

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

Thank you for reading this article so far. If you have any question or feedback or doubt, feel free to ask in comments. 

1 comment:

  1. Use WebClient instead of RestTemplate, and if you are in core Java, you can use HttpClient also

    ReplyDelete