如何使用 HTTPBuilder 在 Groovy 中设置 GET-Response
Posted
技术标签:
【中文标题】如何使用 HTTPBuilder 在 Groovy 中设置 GET-Response【英文标题】:How to set up a GET-Response in Groovy using HTTPBuilder 【发布时间】:2015-11-10 09:54:49 【问题描述】:我的 YouTrack 服务器中存储了几个问题,我想提取这些问题并将信息打包到字符串中。
我已经使用过 RESTClient,但是我得到了错误的输出,因此想尝试一种不同的方法来使用 HttpBuilder 提取问题并在 JSON 中格式化 xml 响应。但是我还不知道如何在 Groovy 中做到这一点(可能是因为我缺少一个完整的运行示例):
经过this website 和this
我希望我的代码看起来像这样:
def http = new HTTPBuilder('http://www.MyYouTrackServer.com')
AuthenticateMe() // I need that, otherwise I cannot access my server
http.get( path : 'MyIssue-25',
contentType : JSON,
query : [???'] ) resp, reader ->
....
// This gap has to be filled somehow,
// so that I have a JSONObject or JSONArray, I can work with.
....
println 'Response data: -----'
System.out << reader
println '\n--------------------'
String str; // this is the important String containing the data
感谢任何建设性的建议、回答或评论。
然后响应将如下所示:
<issues>
<issue>
<comment created="1277899067543" text="is it something wrong?" author="root"/>
<field name="numberInProject"><value>0</value></field>
<field name="summary"><value>susjs</value></field>
<field name="priority"><value>1</value></field>
<field name="description"><value>at jsjsjsj.mps.E.java at line 12</value></field>
<field name="created"><value>1277392628191</value></field>
<field name="updated"><value>1277399118476</value></field>
<field name="reporterName"><value>root</value></field>
<field name="updaterName"><value>root</value></field>
<field name="state"><value>Submitted</value></field>
<field name="subsystem"><value>No subsystem</value></field>
<field name="fixedInBuild"><value>Next build</value></field>
<field name="permittedGroup"><value>All Users</value></field>
</issue>
</issues>
【问题讨论】:
我很乐意帮助您将 XML 响应转换为 JSON,但我需要您发布一个我可以使用的 XML 响应。 谢谢,很多:我在我的帖子中添加了一个示例回复。 【参考方案1】:为了实现您的目标,您可以使用以下方法来处理 json:
import groovyx.net.http.HTTPBuilder
def http = new HTTPBuilder('http://www.MyYouTrackServer.com')
...
http.get( path : '/MyIssue-25',
contentType : 'application/json'
) resp, reader ->
// inside reader you've your json object in `net.sf.json.JSONObject` instance
println reader
考虑到get()
方法的query
参数是可选的,该参数用于查询方法url,如https://twitter.com/search?q=asd
,在这种情况下查询参数将为query : [ q : 'asd' ]
。
所以回到代码,在reader
对象中,您有一个net.sf.json.JSONObject
的实例可以使用,看看its API。
为了展示一个小例子,我在http://localhost/index.json 有一个服务器,它返回跟随 json "a":"a", "b": "b1":"b1", "b2":"b2" , "c":"c"
以使用以下代码:
import groovyx.net.http.HTTPBuilder
def http = new HTTPBuilder('http://localhost')
http.get( path : '/index.json',
contentType : 'application/json'
) resp, reader ->
// cast the object it's not necessary... I cast it
// to have the method suggestions by IDE
net.sf.json.JSONObject read = reader
println read.get("a") // prints "a"
println read.get("b").get("b1") // prints "b1"
//...
// you can also use this approach
println read.a // prints "a"
println read.b.b1 // prints "b1"
println read.b // prints [b1:b1, b2:b2]
更新
我再次阅读了您的问题,根据您的描述,您似乎正在尝试以xml
格式阅读来自YourTrack 的问题。为此,它与json
非常相似,在这种情况下,reader
对象是GPathResult
的一个实例,请查看以下示例,假设您的回复看起来像您在问题中提出的回复:
http = new HTTPBuilder('http://www.MyYouTrackServer.com')
http.get( path : '/MyIssue-25',
contentType : 'application/xml'
) resp, reader ->
// since your response is an xml now in reader you've GPathResult
// and now some samples on how to work with the response:
// get the text of each <field>
def fields = reader.issue.field*.text();
fields.each
print "$it " // prints 0 susjs 1 at jsjsjsj.mps.E.java at line 12 1277392628191 1277399118476 root root Submitted No subsystem Next build All Users numberInProject
// another sample... get the name attribute value for the <field> elements
def namesAttr = reader.issue.field*.@name
namesAttr.each
print "$it " // prints numberInProject summary priority description created updated reporterName updaterName state subsystem fixedInBuild permittedGroup
// find the <field> value for element which has attribute name="state"
def field = reader.issue.'*'.findAll
it.@name == 'state'
println field.text() // prints submitted
同样在这个YourTrack
operation 中似乎有两个查询参数(项目和最大值)可以使用它,您可以将查询参数添加到get()
方法,即:query : [ max : '15' ]
。
希望对你有帮助,
【讨论】:
【参考方案2】:以下是如何将 XML 响应转换为 JSON 对象的方法。注意:我在 XML 响应中添加了一个附加问题,以更好地展示输出。
import groovy.util.XmlParser
import groovy.json.JsonBuilder
def text = '''
<issues>
<issue>
<comment created="1277899067543" text="is it something wrong?" author="root"/>
<field name="numberInProject"><value>0</value></field>
<field name="summary"><value>susjs</value></field>
<field name="priority"><value>1</value></field>
<field name="description"><value>at jsjsjsj.mps.E.java at line 12</value></field>
<field name="created"><value>1277392628191</value></field>
<field name="updated"><value>1277399118476</value></field>
<field name="reporterName"><value>root</value></field>
<field name="updaterName"><value>root</value></field>
<field name="state"><value>Submitted</value></field>
<field name="subsystem"><value>No subsystem</value></field>
<field name="fixedInBuild"><value>Next build</value></field>
<field name="permittedGroup"><value>All Users</value></field>
</issue>
<issue>
<comment created="1277899067543" text="does this work?" author="root"/>
<field name="numberInProject"><value>0</value></field>
<field name="summary"><value>susjs</value></field>
<field name="priority"><value>1</value></field>
<field name="description"><value>at jsjsjsj.mps.E.java at line 12</value></field>
<field name="created"><value>1277392628191</value></field>
<field name="updated"><value>1277399118476</value></field>
<field name="reporterName"><value>root</value></field>
<field name="updaterName"><value>root</value></field>
<field name="state"><value>Submitted</value></field>
<field name="subsystem"><value>No subsystem</value></field>
<field name="fixedInBuild"><value>Next build</value></field>
<field name="permittedGroup"><value>All Users</value></field>
</issue>
</issues>'''
def xml = new XmlParser().parseText(text)
def json = new JsonBuilder()
json xml.issue.inject([]) list, issue ->
def map = [:]
map.comment = [
created: issue.comment["@created"][0],
text: issue.comment["@text"][0],
author: issue.comment["@author"][0],
]
issue.field.each field ->
map[field['@name']] = field.value[0].children()[0]
list << map
return list
json.toString()
json.toString() 的漂亮格式输出(感谢 TextMate)是这样的:
[
"comment":
"author": "root",
"created": "1277899067543",
"text": "is it something wrong?"
,
"created": "1277392628191",
"description": "at jsjsjsj.mps.E.java at line 12",
"fixedInBuild": "Next build",
"numberInProject": "0",
"permittedGroup": "All Users",
"priority": "1",
"reporterName": "root",
"state": "Submitted",
"subsystem": "No subsystem",
"summary": "susjs",
"updated": "1277399118476",
"updaterName": "root"
,
"comment":
"author": "root",
"created": "1277899067543",
"text": "does this work?"
,
"created": "1277392628191",
"description": "at jsjsjsj.mps.E.java at line 12",
"fixedInBuild": "Next build",
"numberInProject": "0",
"permittedGroup": "All Users",
"priority": "1",
"reporterName": "root",
"state": "Submitted",
"subsystem": "No subsystem",
"summary": "susjs",
"updated": "1277399118476",
"updaterName": "root"
]
我将 XML 转换为我认为更合理的数据表示形式。
【讨论】:
以上是关于如何使用 HTTPBuilder 在 Groovy 中设置 GET-Response的主要内容,如果未能解决你的问题,请参考以下文章