11

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]

robert trudel
  • 5,283
  • 17
  • 72
  • 124

2 Answers2

17

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());
cstroe
  • 3,740
  • 3
  • 27
  • 16
6

Http Patch is not supported by HttpUrlConnection. See this

Way to solve this is to configure rest template to use spring's HttpComponentsClientHttpRequestFactory.

RestTemplateBuilder exposes requestfactory setter which should be used to do this.

ritesh.garg
  • 3,725
  • 1
  • 15
  • 14
  • 1
    i was in java 6... 2013... a bit old – robert trudel Jan 03 '17 at 21:33
  • 1
    Yea. Thats when Patch was recently introduced. And they decided to mark it as a won't fix. Having said that, Spring and apache does provide support for Patch by internally handling it as a Put. In order to use spring for that, you need to use spring's client http request factory (like i mentioned in my answer) – ritesh.garg Jan 03 '17 at 22:01