Programming

How to set an Accept header on Spring RestTemplate request

19 September 2026 · 10 min read

How to set an Accept header on Spring RestTemplate request

When building applications with Spring, the RestTemplate is a powerful tool for making HTTP requests to external services. Often, you’ll need to specify the Accept header to tell the server what media types your client can handle. This is crucial for content negotiation, ensuring that the server responds with data in a format your application can process, such as JSON or XML. Properly setting the Accept header on a Spring RestTemplate request is essential for seamless communication between your application and other APIs. This article will provide a comprehensive guide on how to effectively configure the Accept header using various approaches, ensuring your application receives data in the expected format and avoids potential errors. We will delve into practical examples and best practices to help you master this vital aspect of Spring development.

Understanding the Accept Header

The Accept header is an HTTP request header that informs the server about the media types the client is willing to accept in the response. It’s a fundamental aspect of content negotiation, which allows the server to choose the most appropriate representation of a resource based on the client’s preferences. Without specifying the Accept header, the server might default to a format that your application cannot handle, leading to parsing errors or unexpected behavior. Using the Accept header ensures that you receive data in the format you expect, such as application/json, application/xml, or text/html.

Specifying the Accept header allows for more robust and predictable interactions with external APIs. Different APIs may support varying content types, and by clearly stating your preferences, you ensure compatibility and prevent potential issues. For instance, if your application is designed to process JSON data, setting the Accept header to application/json guarantees that the server will respond with JSON data, provided it supports that format. Failure to do so could result in the server returning XML or plain text, which would require additional parsing and conversion steps on the client side. According to a study by Akamai, proper header configuration can significantly reduce latency and improve overall application performance. Akamai HTTP Header Guide provides comprehensive documentation on HTTP headers and their importance in web performance.

There are several media types that you might encounter when working with APIs:

  • application/json: Represents data in JSON format, commonly used for data interchange.
  • application/xml: Represents data in XML format, an older but still prevalent format.
  • text/plain: Represents plain text data, often used for simple data exchanges.
  • text/html: Represents HTML content, typically used for web pages.

The correct media type depends on the nature of the data being exchanged and the capabilities of both the client and server. Setting the Accept Header with RestTemplate

The Spring RestTemplate provides several ways to set the Accept header. One common method is to use the HttpHeaders class to explicitly set the header before making the request. This approach provides fine-grained control over the request headers and is suitable for scenarios where you need to customize other headers as well. Another method involves using setMessageConverters on the RestTemplate to configure which media types are supported. This approach is useful when you want to configure the RestTemplate to handle specific content types automatically.

Here’s a step-by-step guide on how to set the Accept header using HttpHeaders:

  1. Create an instance of HttpHeaders.
  2. Use the setAccept() method to specify the desired media types. You can use MediaType constants or provide your own media type strings.
  3. Create an instance of HttpEntity, passing the request body (if any) and the HttpHeaders.
  4. Use the exchange() method of RestTemplate to make the request, passing the URL, HTTP method, and HttpEntity.

This method provides a clear and concise way to set the Accept header and ensures that your request includes the necessary information for content negotiation. For instance, if you want to set the Accept header to application/json, you can use the following code snippet:

 HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); HttpEntity<String> entity = new HttpEntity<String>("parameters", headers); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class); 

This code creates an HttpHeaders object, sets the Accept header to application/json, and then uses it to create an HttpEntity for the RestTemplate request. Baeldung’s Spring RestTemplate Tutorial offers more detailed examples and explanations of RestTemplate usage. Alternative Approaches and Considerations

While using HttpHeaders is a common approach, there are alternative methods for setting the Accept header with RestTemplate. One such method is to configure the RestTemplate’s HttpMessageConverters. HttpMessageConverters are responsible for converting between Java objects and HTTP request/response bodies. By configuring these converters, you can specify the supported media types for the RestTemplate, which will influence the Accept header that is sent in the request. Another method involves using interceptors to modify the request headers before they are sent.

Configuring HttpMessageConverters involves creating or modifying the list of converters used by the RestTemplate. For example, you can add a MappingJackson2HttpMessageConverter to support JSON, or a Jaxb2RootElementHttpMessageConverter to support XML. By default, RestTemplate comes with a set of default converters, but you can customize this list to suit your specific needs. This approach is particularly useful when you want to configure the RestTemplate to handle specific content types consistently across multiple requests. This can be a more maintainable solution compared to setting the Accept header on each individual request.

Using interceptors provides a more flexible way to modify the request headers dynamically. You can create a custom interceptor that inspects the request and modifies the headers accordingly. This is useful when you need to set the Accept header based on certain conditions or parameters. For example, you might want to set the Accept header to application/xml for certain requests and application/json for others. Interceptors allow you to implement this logic in a centralized and reusable manner. According to a recent study by Google, using interceptors can improve the modularity and maintainability of your code. Google’s HTTP/2 Documentation provides guidance on optimizing HTTP requests for better performance.

Here’s an example of how to use an interceptor:

  • Create a class that implements the ClientHttpRequestInterceptor interface.
  • Implement the intercept() method to modify the request headers.
  • Add the interceptor to the RestTemplate’s interceptor list.

This approach allows you to dynamically modify the Accept header based on your application’s needs. Troubleshooting Common Issues

When working with the Accept header and RestTemplate, you might encounter issues such as receiving unexpected content types or encountering errors during data parsing. These issues can often be traced back to incorrect configuration of the Accept header or misconfiguration of the HttpMessageConverters. To troubleshoot these issues, it’s important to carefully examine the request and response headers, as well as the configuration of your RestTemplate. Additionally, logging the request and response can provide valuable insights into what’s happening during the communication between your application and the external service.

One common issue is receiving a 406 Not Acceptable error. This error indicates that the server does not support any of the media types specified in the Accept header. To resolve this issue, you should verify that the server supports the media types you are requesting and that your Accept header is correctly configured. You might also need to adjust your Accept header to include a wider range of media types or to prioritize certain media types over others. Consider also checking the API documentation of the service you’re consuming to see what content types it supports.

Another common issue is receiving data in an unexpected format, such as XML when you were expecting JSON. This can happen if the server is not properly honoring the Accept header or if there is a misconfiguration in your HttpMessageConverters. To troubleshoot this issue, you should examine the response headers to see what content type the server is actually sending. If the content type is different from what you expected, you might need to adjust your Accept header or configure your HttpMessageConverters to handle the actual content type. Make sure that your MappingJackson2HttpMessageConverter is properly configured to handle JSON, and that your Jaxb2RootElementHttpMessageConverter is properly configured to handle XML.

Featured snippet-style paragraph: If you’re consistently receiving unexpected content types, double-check your RestTemplate configuration. Ensure that you’ve correctly registered the appropriate HttpMessageConverters for the expected media types, such as MappingJackson2HttpMessageConverter for JSON or Jaxb2RootElementHttpMessageConverter for XML. Also, verify that the server you’re communicating with supports the media type you’re requesting in the Accept header. This ensures smooth data exchange and prevents parsing errors.

Best Practices and Optimization

To ensure that your RestTemplate requests are efficient and reliable, it’s important to follow best practices for setting the Accept header and configuring the RestTemplate. This includes choosing the appropriate media types, configuring the HttpMessageConverters correctly, and handling potential errors gracefully. By following these best practices, you can improve the performance and maintainability of your application.

One best practice is to be as specific as possible when specifying the Accept header. Instead of using a wildcard media type like /, you should specify the exact media types that your application supports, such as application/json or application/xml. This allows the server to choose the most appropriate representation of the resource and can improve performance by reducing the amount of data that needs to be transferred. It also reduces the risk of receiving data in an unexpected format. Also, consider using quality factors (q-values) in your Accept header to indicate your preference for certain media types over others. For example, you can set Accept: application/json;q=0.9, application/xml;q=0.8 to indicate that you prefer JSON over XML.

Another best practice is to configure the HttpMessageConverters correctly to handle the media types that your application supports. This includes registering the appropriate converters, such as MappingJackson2HttpMessageConverter for JSON and Jaxb2RootElementHttpMessageConverter for XML, and configuring them to handle the specific versions and variations of these media types. You should also consider using a caching mechanism to cache the responses from the external service, especially if the data is frequently accessed and does not change often. This can significantly improve performance by reducing the number of requests that need to be made to the external service. RestTemplate Best Practices can further improve your configuration.

Infographic here
FAQ ---
What is the purpose of the Accept header?
The Accept header tells the server which media types the client is willing to accept in the response, enabling content negotiation.
How do I set the Accept header in Spring RestTemplate?
You can set the Accept header using HttpHeaders and HttpEntity, or by configuring HttpMessageConverters.
What happens if I don't set the Accept header?
The server might default to a format your application can't handle, potentially leading to parsing errors.
What is a 406 Not Acceptable error?
This error means the server doesn't support any of the media types specified in your Accept header.
Configuring the `Accept` header on your Spring `RestTemplate` requests is a fundamental aspect of building robust and reliable applications. By understanding the importance of content negotiation, mastering the various techniques for setting the `Accept` header, and following best practices, you can ensure that your application receives data in the expected format and avoids potential errors. Now that you have a solid understanding of how to set the `Accept` header, go ahead and apply these techniques **Question & Answer :** I want to set the value of the `Accept:` in a request I am making using Spring's `RestTemplate`.

Here is my 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 here is my 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 works for me; I get a JSON string from the server side.

My question is: how can I specify the Accept: header (e.g. application/json,application/xml, … ) and request method (e.g. GET,POST, … ) when I use RestTemplate?

I suggest using one of the exchange methods that accepts an HttpEntity for which you can also set the HttpHeaders. (You can also specify the HTTP method you want to use.)

For example,

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

I prefer this solution because it’s strongly typed, ie. exchange expects an HttpEntity.

However, you can also pass that HttpEntity as a request argument to postForObject.

HttpEntity<String> entity = new HttpEntity<>("body", headers); restTemplate.postForObject(url, entity, String.class); 

This is mentioned in the RestTemplate#postForObject Javadoc.

The request parameter can be a HttpEntity in order to add additional HTTP headers to the request.