Complete Guide to Setting Accept Header in Spring RestTemplate

Nov 11, 2025 · Programming · 18 views · 7.8

Keywords: Spring | RestTemplate | Accept Header | HTTP Request | REST Client

Abstract: This article provides an in-depth exploration of various methods to set Accept headers in Spring RestTemplate, focusing on strongly-typed solutions using HttpEntity and exchange methods with detailed code examples and best practices. It also covers supplementary approaches using interceptors for global header configuration, helping developers master HTTP header management in RestTemplate.

Introduction

In Spring-based REST API development, RestTemplate is one of the most commonly used tools for service invocation. In practical applications, it's often necessary to set HTTP request headers, particularly the Accept header, to specify the expected response content type. This article systematically introduces multiple methods for setting Accept headers in RestTemplate.

Problem Context

Consider the following typical Spring MVC controller 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;
}

The corresponding client invocation code:

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

While this code works correctly and retrieves JSON responses, developers often need to explicitly specify Accept headers and HTTP methods.

Core Solution: Using HttpEntity and Exchange Method

The most recommended approach is using RestTemplate's exchange method, which accepts HttpEntity parameters and allows flexible configuration of HTTP headers and request methods.

Basic Implementation

Here's a complete example setting the Accept header to application/json:

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

Solution Advantages

The strength of this approach lies in its strong typing: the exchange method explicitly expects HttpEntity parameters, providing compile-time type safety. Additionally, this method allows developers to specify concrete HTTP methods (GET, POST, PUT, DELETE, etc.), enhancing code flexibility and readability.

Alternative Approach: Using postForObject Method

Besides the exchange method, HttpEntity can also be passed as a request parameter to the postForObject method:

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

According to Spring official documentation, the request parameter can be an HttpEntity type to add additional HTTP headers to the request.

Supplementary Approach: Using Interceptors for Global Configuration

For scenarios requiring repeated use of the same header configuration across multiple requests, ClientHttpRequestInterceptor can be used to implement global header management.

Custom Interceptor Implementation

Create a custom header interceptor:

public class HeaderRequestInterceptor implements ClientHttpRequestInterceptor {

    private final String headerName;
    private final String headerValue;

    public HeaderRequestInterceptor(String headerName, String headerValue) {
        this.headerName = headerName;
        this.headerValue = headerValue;
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        request.getHeaders().set(headerName, headerValue);
        return execution.execute(request, body);
    }
}

Interceptor Configuration and Usage

Configure RestTemplate to use the custom interceptor:

List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
interceptors.add(new HeaderRequestInterceptor("Accept", MediaType.APPLICATION_JSON_VALUE));

RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(interceptors);

This approach is suitable for scenarios requiring uniform setting of specific HTTP headers throughout the application, avoiding repetitive header-setting code in each request.

Advanced Application Scenarios

Multiple Content Type Support

In practical applications, clients may need to support multiple content types. This can be achieved by setting multiple MediaTypes:

HttpHeaders headers = new HttpHeaders();
List<MediaType> acceptableMediaTypes = new ArrayList<>();
acceptableMediaTypes.add(MediaType.APPLICATION_JSON);
acceptableMediaTypes.add(MediaType.APPLICATION_XML);
headers.setAccept(acceptableMediaTypes);

Complete GET Request Example

Here's a complete GET request example including query parameters and custom headers:

String url = "https://api.example.com/search?q={query}";
RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.set("X-Request-Source", "Desktop");

HttpEntity<String> request = new HttpEntity<>(headers);

ResponseEntity<String> response = restTemplate.exchange(
    url,
    HttpMethod.GET,
    request,
    String.class,
    "java"
);

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

Best Practice Recommendations

1. Prioritize Type Safety: Recommend using the exchange method as it provides better type safety and flexibility.

2. Header Management Strategy: Choose appropriate header management strategies based on application requirements. Use interceptors for globally uniform header configuration, and HttpEntity for request-specific header configuration.

3. Error Handling: Always check HTTP response status codes to ensure successful request processing.

4. Content Negotiation: Properly set Accept headers to support server-side content negotiation mechanisms.

Conclusion

This article has detailed various methods for setting Accept headers in Spring RestTemplate. The core solution involves strongly-typed header configuration through HttpEntity and exchange methods, which is not only secure and reliable but also offers maximum flexibility. For scenarios requiring global header management, ClientHttpRequestInterceptor serves as a supplementary approach. Mastering these techniques will help developers build more robust REST client applications.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.