我使用以下代码对外部系统执行HTTP POST。问题是当使用下面的代码时,外部系统总是获得'null'内容类型。有没有办法在使用HTTPBuilder时设置contenttype。
我尝试了执行相同请求的其他工具,但远程系统获得了良好的contentType('application / json')。
def execute(String baseUrl, String path, Map requestHeaders=[:], Map query=[:], method = Method.POST) {
try {
def http = new HTTPBuilder(baseUrl)
def result = null
// perform a ${method} request, expecting TEXT response
http.request(method, ContentType.JSON) {
uri.path = path
uri.query = query
// add possible headers
requestHeaders.each { key, value ->
headers."${key}" = "${value}"
}
// response handler for a success response code
response.success = { resp, reader ->
result = reader.getText()
}
}
return result
} catch (groovyx.net.http.HttpResponseException ex) {
ex.printStackTrace()
return null
} catch (java.net.ConnectException ex) {
ex.printStackTrace()
return null
}
}
答案 0 :(得分:1)
在请求中添加特定标头似乎可以解决我的问题。
def execute(String baseUrl, String path, Map requestHeaders=[:], Map query=[:], method = Method.POST) {
try {
def http = new HTTPBuilder(baseUrl)
def result = null
// perform a ${method} request, expecting TEXT response
http.request(method, ContentType.JSON) {
uri.path = path
uri.query = query
headers.'Content-Type' = 'application/json'
// add possible headers
requestHeaders.each { key, value ->
headers."${key}" = "${value}"
}
// response handler for a success response code
response.success = { resp, reader ->
result = reader.getText()
}
}
return result
} catch (groovyx.net.http.HttpResponseException ex) {
ex.printStackTrace()
return null
} catch (java.net.ConnectException ex) {
ex.printStackTrace()
return null
}
}
答案 1 :(得分:0)
尝试在请求块的正文中设置requestContentType ...
http.request(method, ContentType.JSON) {
uri.path = path
uri.query = query
requestContentType = groovyx.net.http.ContentType.URLENC
.......
}