带有 PATCH 请求方法的 Grails 'grails-rest-client-builder' 插件

Grails 'grails-rest-client-builder' plugin with PATCH request method

我正在使用 grails2.4.4 和 grails-rest-client-builder: 2.0.0 插件。我需要调用一个接受请求方法 PATCH 的 REST URL。但我无法使用这个插件: 我正在使用以下代码:

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

我遇到以下错误:

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     ''

谁能帮帮我?

好的。经过多次尝试和错误,终于成功了。默认 java.net.HttpURLConnection 不支持像 PATCH 这样的自定义请求方法,我收到了那个错误。所以我需要寻找一些支持此类请求方法的第三方库,例如commons-httpclient。所以我注入了 commons-httpclient(now it is named as apache-httpcomponents) 以使其与 PATCH 请求方法一起使用。

以下是我为使其工作所做的更改:

首先在grails中添加依赖BuildConfig.groovy

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

解决方案#1

如果您想通过手动创建对象:

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

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

解决方案#2

使用 Grails-Spring 注入:

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'))
}

在你的 class 中注入 restBuilder:

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
   }

}

希望这对某人有所帮助。