Resttemplate and patch, invalid

robert trudel picture robert trudel · Dec 28, 2016 · Viewed 7.4k times · Source

I use spring 1.4.3

I try to call a web service

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

In my application,

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

}

In another method I do

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

I get this error

java.net.ProtocolException: Invalid HTTP method: 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]

Answer

cstroe picture cstroe · Oct 5, 2018

Building on ritesh.garg's answer:

Add the following dependency to your classpath:

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

Then, create your RestTemplate like this:

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