Resttemplate和补丁,无效

时间:2016-12-28 19:48:46

标签: spring-boot resttemplate spring-restcontroller

我使用spring 1.4.3

我尝试拨打网络服务

  @PatchMapping(value = "/members/{memberId}/card")
  public ResponseEntity updateMemberCardId(@PathVariable("memberId") Long memberId, @RequestBody String cardId) throws ResourceNotFoundException {
        memberService.updateMemberCardId(cardId, memberId);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
  }

在我的申请中,

@Component
@Configuration
public class ClientRestConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder, @Value("${main.server.url}") String mainServerUrl, @Value("${commerce.username}") String commerceUsername, @Value("${commerce.password}") String commercePassword,  @Value("${connection.timeout}") int timeout) {
        return builder.setConnectTimeout(timeout).setReadTimeout(timeout).basicAuthorization(commerceUsername, commercePassword).rootUri(mainServerUrl).build();
    }

}

我用另一种方法

String cardId = "123456789";

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(cardId, headers);

ResponseEntity responseEntity =  restTemplate.patchForObject("/rest/members/1/card", entity, ResponseEntity.class);

我收到此错误

  

java.net.ProtocolException:无效的HTTP方法:PATCH at   java.net.HttpURLConnection.setRequestMethod(HttpURLConnection.java:440)   〜[na:1.8.0_111] at   sun.net.www.protocol.http.HttpURLConnection.setRequestMethod(HttpURLConnection.java:552)   〜[NA:1.8.0_111]

2 个答案:

答案 0 :(得分:3)

HttpUrlConnection不支持Http Patch。见this

解决此问题的方法是配置rest模板以使用spring的HttpComponentsClientHttpRequestFactory。

RestTemplateBuilder公开了应该用于执行此操作的requestfactory setter。

答案 1 :(得分:1)

基于ritesh.garg的答案:

将以下dependency添加到您的类路径中:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version>
</dependency>

然后,像这样创建您的RestTemplate

    RestTemplate template = new RestTemplate(new HttpComponentsClientHttpRequestFactory());