【问题标题】:Grails 'grails-rest-client-builder' plugin with PATCH request method带有 PATCH 请求方法的 Grails 'grails-rest-client-builder' 插件
【发布时间】:2015-01-16 16:37:37
【问题描述】:

我正在使用 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     ''

谁能帮帮我?

【问题讨论】:

    标签: grails-plugin grails-2.4 restclientbuilder


    【解决方案1】:

    好的。经过几次尝试和错误,终于成功了。默认 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'))
    }
    

    在你的班级中注入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
       }
    
    }
    

    希望这对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多