如何在Spring RestTemplate请求上设置“Accept:”标题?

我想设置Accept:的值Accept:在我使用Spring的RestTemplateRestTemplate

这是我的Spring请求处理代码

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

这里是我的Java REST客户端:

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

这适用于我; 我从服务器端得到一个JSONstring。

我的问题是:当我使用RestTemplate时,如何指定Accept:头(例如application/jsonapplication/xml ,…)和请求方法(例如GETPOST ,…)?

我build议使用接受HttpEntityexchange方法之一,也可以设置HttpHeaders 。 (您也可以指定要使用的HTTP方法。)

例如,

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

我更喜欢这个解决scheme,因为它是强types的,即。 exchange期望一个HttpEntity

但是,您也可以将该HttpEntity作为requestparameter passing给postForObject

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

这在RestTemplate#postForObject Javadoc中提到。

request参数可以是HttpEntity ,以便为请求添加额外的HTTP头

您可以在RestTemplate中设置一个拦截器“ClientHttpRequestInterceptor”,以避免每次发送请求时设置标题。

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

然后

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

如果像我一样努力寻找一个使用基本身份validation和其他模板交换API的示例,这就是我最终devise出来的…

 private HttpHeaders createHttpHeaders(String user, String password) { String notEncoded = user + ":" + password; String encodedAuth = Base64.getEncoder().encodeToString(notEncoded.getBytes()); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Basic " + encodedAuth); return headers; } private void doYourThing() { String theUrl = "http://blah.blah.com:8080/rest/api/blah"; RestTemplate restTemplate = new RestTemplate(); try { HttpHeaders headers = createHttpHeaders("fred","1234"); HttpEntity<String> entity = new HttpEntity<String>("parameters", headers); ResponseEntity<String> response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, String.class); System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody()); } catch (Exception eek) { System.out.println("** Exception: "+ eek.getMessage()); } }