尝试通过HttpBuilder将JSON POST到REST URL时的另一个问题

时间:2013-08-07 23:43:46

标签: json groovy httpbuilder

我在SO和其他地方阅读了this和其他几个关于如何通过HttpBuilder发送Post调用以及JSON作为数据内容的帖子。我的问题是没有这些解决方案正在运作!

我的问题只是略有不同。 我在文件中存在JSON数据。 当我尝试使用curl将其发送到REST接口时:

curl -X POST -u "username:password" -d @/path/to/myFile.json http://localhost:8080/path/here --header "Content-Type:application/json"

一切都很好。这是我所在的地方(在那里有一些额外的代码,请继续阅读):

def myFile = new File('/path/to/myFile.json')
if (!myFile.exists()) println "ERROR!  Do not have JSON file!"

def convertedText = myFile.text.replaceAll('\\{', '[')
convertedText = convertedText.replaceAll('\\}', ']') 

def jsonBldr = new JsonBuilder()
jsonBldr myFile.text

println jsonBldr.toString()

def myClient = new groovyx.net.http.HTTPBuilder('http://username:password@localhost:8080/my/path')
myClient.setHeaders(Accept: 'application/json')

results = myClient.request(POST, JSON) { req ->
    body = [ jsonBldr.toString() ]
    requestContentType = JSON
    response.success = { resp, reader ->
        println "SUCCESS! ${resp.statusLine}"
    }

    response.failure = { resp ->
        println "FAILURE! ${resp.properties}"
    }
}

这会导致此数据“失败”关闭:

statusLine:HTTP/1.1 400 Exception evaluating property 'id' for java.util.ArrayList, Reason: groovy.lang.MissingPropertyException: No such property: id for class: java.lang.String

FWIW,我的JSON中没有任何“id”。如果我将“body”行从“[jsonBldr.toString()]”更改为“[convertedText]” - 这就是为什么代码在那里,我得到相同的错误。如果我取出正文上的括号,我会收到一个错误,指出正文不是数组的数据(就像它的地图一样)。

任何人(比我更远)都可以告诉我%% $#@我做错了什么???

1 个答案:

答案 0 :(得分:4)

您需要JsonSlurper而不是JsonBuilder。之后实现如下:

def myFile = new File('/path/to/myFile.json')
if (!myFile.exists()) println "ERROR!  Do not have JSON file!"

def bodyMap = new JsonSlurper().parseText(myFile.text)

def myClient = new groovyx.net.http.HTTPBuilder('http://username:password@localhost:8080/my/path')
modelClient.setHeaders(Accept: 'application/json')

results = myClient.request(POST, JSON) { req ->
    requestContentType = JSON
    body = bodyMap
    response.success = { resp, reader ->
        println "SUCCESS! ${resp.statusLine}"
    }

    response.failure = { resp ->
        println "FAILURE! ${resp.properties}"
    }
}

但是,我不清楚代码中myFilemodelFile之间的区别。