Groovy RestClient没有为内容类型:application/json使用正确的响应处理程序?

Groovy RestClient没有为内容类型:application/json使用正确的响应处理程序?,rest,http,groovy,http-headers,httpresponse,Rest,Http,Groovy,Http Headers,Httpresponse,我使用Groovy向服务器发送一些纯文本,我得到的响应是JSON,但我在弄清楚为什么响应被解析为对象而不是对象时遇到了一些问题 据我所知,响应主体应该根据响应头中的内容类型解析为对象,我得到的响应头是application/json,但它似乎默认为并将响应解析为StringReader对象。我不确定是否定义了错误的标题,或者是否需要指定自己的成功处理程序??我还有其他使用POST方法的方法,它们可以很好地工作,但是它们发布XML并期望XML作为响应,所以我认为在这种情况下,标题工作得很好 下面是

我使用Groovy向服务器发送一些纯文本,我得到的响应是JSON,但我在弄清楚为什么响应被解析为对象而不是对象时遇到了一些问题

据我所知,响应主体应该根据响应头中的内容类型解析为对象,我得到的响应头是
application/json
,但它似乎默认为并将响应解析为
StringReader
对象。我不确定是否定义了错误的标题,或者是否需要指定自己的成功处理程序??我还有其他使用POST方法的方法,它们可以很好地工作,但是它们发布XML并期望XML作为响应,所以我认为在这种情况下,标题工作得很好

下面是我如何尝试它和我的日志,正如您可以看到的,响应头
内容类型
application/json
,所以我不明白为什么
restClientResponse.getData()
StringReader
对象而不是
JsonSlurper
对象

def restClient = new RESTClient("http://this.doesnt.matter", 'text/plain')

restClient.setProxy("someproxy", 8080, "http")
restClient.setHeaders(Accept: "application/json")

def restClientResponse = restClient.post(body: "requestPayload:ACCOUNTPROFILE")
log.info(restClientResponse.getData())
log.info("What is in StringReader")

//Printing out what is in StringReader Object
def reader = restClientResponse.getData()
StringBuilder builder = new StringBuilder()
char[] characters = new char[1000]
builder.append(characters, 0, reader.read(characters, 0, characters.length))
log.info(builder.toString())

// Printing out each header in the response
restClientResponse.getAllHeaders().each {
    log.info("HEADER: " + it.getName() + ":" + it.getValue())
}

return restClientResponse.getData()
日志:


关于为什么响应主体没有被解析为
JsonSlurper
对象,有什么想法吗?

解决方案是从
RESTClient
构造函数中删除Content-Type参数,并在post参数中指定
requestContentType
,如下所示:

def restClient = new RESTClient("http://this.doesnt.matter")
...
def restClientResponse = restClient.post(
    body:"requestPayload:ACCOUNTPROFILE",
    requestContentType: 'text/plain'
)
问题是我(缺乏)理解为
RESTClient
构造函数提供默认内容类型的作用。我假设,通过向
RESTClient
构造函数提供
text/plain
的内容类型,它会在请求头中将内容类型设置为
text/plain
,然后根据响应头中的内容类型计算出响应主体要使用的解析器。但是,我认为,通过向RESTClient提供
text/plain
参数,当它收到响应时,它会忽略响应头中的内容类型,并使用RESTClient构造函数中提供的内容类型

感谢@dmahapatro为我指出问题,这让我阅读了文档的部分

可能重复的内容。尝试将
requestContentType
设置为JSON。
def restClient = new RESTClient("http://this.doesnt.matter")
...
def restClientResponse = restClient.post(
    body:"requestPayload:ACCOUNTPROFILE",
    requestContentType: 'text/plain'
)