我需要使用HTTP PATCH动词使用Spring的RestTemplate调用服务。从我读到的,我需要使用execute()或exchange()方法,但我不知道如何使用它。服务调用返回HTTP 200 OK状态,以及我不是特别感兴趣的JSON对象。
任何帮助将不胜感激。
答案 0 :(得分:4)
可以使用PATCH谓词,但必须使用带有exchange()的RestTemplate类的Apache HTTP客户端库。您可能不需要映射器部分。下面的EmailPatch类仅包含我们要在请求中更新的字段。
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.registerModule(new Jackson2HalModule());
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json"));
converter.setObjectMapper(mapper);
HttpClient httpClient = HttpClients.createDefault();
RestTemplate restTemplate = new RestTemplate(Collections.<HttpMessageConverter<?>> singletonList(converter));
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
EmailPatch patch = new EmailPatch();
patch.setStatus(1);
ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.PATCH, new HttpEntity<EmailPatch>(patch),
String.class);