Java 如何发出 Spring RestTemplate PATCH 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21397416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:28:05  来源:igfitidea点击:

How to make a Spring RestTemplate PATCH request

javaspringresttemplate

提问by Reezy

I need to make a call to a service using Spring's RestTemplate using the HTTP PATCH verb. From what I read I need to use the execute() or exchange() method, but I have no idea on how to use it. The service call returns a HTTP 200 OK status, as well as a JSON object which I'm not particularly interested in.

我需要使用 HTTP PATCH 动词使用 Spring 的 RestTemplate 调用服务。从我读到的内容来看,我需要使用 execute() 或 exchange() 方法,但我不知道如何使用它。服务调用返回一个 HTTP 200 OK 状态,以及一个我不是特别感兴趣的 JSON 对象。

Any help will be appreciated thanks.

任何帮助将不胜感激,谢谢。

回答by Lucas Holt

It is possible to use the PATCH verb, but you must use the Apache HTTP client lib with the RestTemplate class with exchange(). The mapper portion may not be necessary for you. The EmailPatch class below only contains the field we want to update in the request.

可以使用 PATCH 动词,但您必须将 Apache HTTP 客户端库与 RestTemplate 类与 exchange() 一起使用。您可能不需要映射器部分。下面的 EmailPatch 类只包含我们要在请求中更新的字段。

  ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Hymanson2HalModule());

    MappingHymanson2HttpMessageConverter converter = new MappingHymanson2HttpMessageConverter();
    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);