1

I'm using grails2.4.4 and grails-rest-client-builder: 2.0.0 plugin. I need to invoke a REST URL which accepts request method, PATCH. But i'm not able to do with this plugin: I'm using below code:

def rest = new RestBuilder()
def resp = rest.patch("$URL") {
    header 'Authorization', "Bearer $accessToken"
}

I'm getting below error:

Invalid HTTP method: PATCH. Stacktrace follows:
 Message: Invalid HTTP method: PATCH
 Line | Method
  440 | setRequestMethod    in java.net.HttpURLConnection
  307 | invokeRestTemplate  in grails.plugins.rest.client.RestBuilder
  280 | doRequestInternal . in     ''

Can anyone please help me out?

erichelgeson
  • 2,310
  • 1
  • 16
  • 24
kaluva
  • 621
  • 8
  • 27

1 Answers1

4

Ok. Finally made it after several trial and errors. As default java.net.HttpURLConnection doesn't support custom request method like PATCH, i'm getting that error. So i need to go for some thirdparty libraries like commons-httpclient which supports such request methods. So i injected commons-httpclient(now it is named as apache-httpcomponents) to make it work with PATCH request method.

Below are the changes i did to make it work:

First add dependency in grails BuildConfig.groovy

runtime "org.apache.httpcomponents:httpclient:4.3.6"

Solution#1

If you want to go by manual object creation:

RestTemplate restTemplate=new RestTemplate()
restTemplate.setRequestFactory(new  HttpComponentsClientHttpRequestFactory());

def rest=new RestBuilder(restTemplate)
def resp = rest.patch("$URL"){
        header 'Authorization', "Bearer $accessToken"
    }

Solution#2

Using Grails-Spring Injection:

Add below configuration in resources.groovy

import grails.plugins.rest.client.RestBuilder
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory
import org.springframework.web.client.RestTemplate

beans={
   httpClientFactory (HttpComponentsClientHttpRequestFactory)
   restTemplate (RestTemplate,ref('httpClientFactory'))
   restBuilder(RestBuilder,ref('restTemplate'))
}

Inject restBuilder in your class:

class MyRestClient{
   def restBuilder

   ....

   def doPatchRequest(){
   def resp=restBuilder.patch("$API_PATH/presentation/publish?id=$presentationId"){
            header 'Authorization', "Bearer $accessToken"
        };

    //do anything with the response
   }

}

Hope this helps someone.

kaluva
  • 621
  • 8
  • 27