如何使用HTTPBuilder

时间:2015-08-17 16:57:27

标签: html json groovy server httpbuilder

我的YouTrack服务器中存储了几个问题,我想提取这些问题并将信息打包在字符串中。

我已经使用过RESTClient,但是输出结果不好,因此想尝试一种不同的方法来使用HttpBuilder提取问题并在JSON中格式化xml响应。但是我还不知道,如何在Groovy中做到这一点(可能是因为我缺少一个完整的,运行的例子):

前往this websitethis

我希望我的代码看起来像这样:

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>

2 个答案:

答案 0 :(得分:2)

为了实现您的目标,您可以使用以下方法来使用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

}

考虑query方法的get()参数,它是可选的,此参数用于查询方法网址,例如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' ]。< / p>

希望这有帮助,

答案 1 :(得分: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转换为我认为更合理的数据表示形式。