当我通过curl执行此操作时:
curl -u -X DELETE -H 'accept:application/json' http://localhost:13000/test/test_userid"
我为httpbuilder创建了一个接受methodtype(GET,POST,DELETE等)和内容类型(JASON,TEXT)的通用函数。
def public httpRequest(String url, String content, Method requestType, ContentType contentType)
{
try{
def myClient = new HTTPBuilder(url)
myClient.request(requestType,contentType) { req ->
headers.'Content-Type' = 'application/json'
body=content
response.success = { resp, data ->
def reponse=[resp:resp,data:data]
return reponse
}
response.failure = { resp ->
println 'Response Code '+resp.statusLine
}
// called only for a 404 (not found) status code:
response.'404' = { resp ->
println 'Not found'
}
}
}
catch(Exception e)
{
println "error"+e.getProperties()
}
}
现在,如果我发出POST请求,它的工作原理。 但是,如果我使用
发出GET或DELETE请求 def response = httpRequest(url,"",DELETE,JSON)
或
def response = httpRequest(url,"",GET,TEXT)
它显示以下错误: -
error[message:Cannot set a request body for a DELETE/GET method, class:class java.lang.IllegalArgumentException
我是否需要为GET / DELETE创建单独的功能? 因为
myClient.request(requestType) { req ->
headers.'Content-Type' = 'application/json'
body=content
response.success = { resp, data ->
def reponse=[resp:resp,data:data]
return reponse
}
response.failure = { resp ->
println 'Response Code '+resp.statusLine
}
// called only for a 404 (not found) status code:
response.'404' = { resp ->
println 'Not found'
}
}
}
WORKS
答案 0 :(得分:0)
删除并获取不会接受Body,因此解决方案是进行检查并相应地执行
if(requestType.equals(DELETE)||requestType.equals(GET))
{
try{
def myClient = new HTTPBuilder(url)
myClient.request(requestType) { req ->
headers.'Content-Type' = 'application/json'
headers.Accept = 'application/json'
response.success = { resp, data ->
def reponse=[resp:resp,data:data]
return reponse
}
response.failure = { resp ->
println 'Response Code '+resp.statusLine
}
// called only for a 404 (not found) status code:
response.'404' = { resp ->
println 'Not found'
}
}
}
catch(Exception e)
{
println "error"+e.getProperties()
}
}
else
<---post request -->