好的。经过几次尝试和错误,终于成功了。默认 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
}
}
希望这对某人有所帮助。