def http = new HTTPBuilder('http://www.baidu.com') http.request(GET,TEXT) { //设置url相关信息 uri.path='/' uri.query=[a:'1',b:2] //设置请求头信息 headers.'User-Agent' = 'Mozill/5.0' //设置成功响应的处理闭包 response.success= {resp,reader-> println resp.status println resp.statusLine.statusCode println resp.headers.'content-length' System.out << reader } //根据响应状态码分别指定处理闭包 response.'404' = { println 'not found' } //未根据响应码指定的失败处理闭包 response.failure = { println "Unexpected failure: ${resp.statusLine}" } }request 方法中有三个参数1、请求方法 2、contenttype 3、 封装请求配置的一个闭包
def http = new HTTPBuilder('http://www.google.com.hk') http.request(GET, TEXT) { uri.path="/search" uri.query = [q:'groovy'] response.success ={resp,reader-> println resp.statusLine.statusCode println resp.headers.'content-length' System.out << reader } response.failure={resp-> println resp.status } }
def http = new HTTPBuilder('http://www.google.com.hk') //简化的get请求 def html = http.get(path:'/search',query:[q:'groovy']) //根据响应的contentType头信息,指定对应的处理方式,html的经过xmlslurper处理后返回的 是GPathResult实例 assert html instanceof groovy.util.slurpersupport.GPathResult assert html.HEAD.size() == 1 assert html.BODY.size() == 12、POST请求
def http = new HTTPBuilder('http://localhost:8080/test') http.request(POST) { uri.path = '/update' body=[name:'berdy'] requestContentType=URLENC response.success={resp-> assert resp.statusLine.statusCode } }上面代码中的body参数指定了post请求提交的参数,requestContentType指定了提交参数的处理类型,
send URLENC, [ name : 'berdy']同样的HTTPBuilder也提供了一个简洁的post请求方式
def http = new HTTPBuilder('http://localhost:8080/test') def postBody = [name:'berdy'] http.post(path:'/update',body:postBody,requestContentType:URLENC){resp-> assert resp.statusLine.statusCode == 200 }3、json格式数据处理;
def http = new HTTPBuilder('http://localhost:8080/test') //根据responsedata中的Content-Type header,调用json解析器处理responsedata http.get(path:'/getJson'){resp,json-> println resp.status json.each{ println it } }处理post请求中的json数据
def http = new HTTPBuilder('http://localhost:8080/test') http.request( POST, JSON ) { req -> uri.path='/postJson' body = [ first : 'berdy', last : 'lengfeng' ] response.success = { resp, json -> // TODO process json data } }也可以使用send()方法处理:
def http = new HTTPBuilder('http://localhost:8080/test') http.request( POST, JSON ) { req -> uri.path='/postJson' send 'text/javascript',[body : [ first : 'berdy', last : 'lengfeng' ]] response.success = { resp, json -> // TODO process json data } }另外,针对ContentType中为定义的类型,可以在parser中注册需要的处理器
http.parser.'text/csv' = { resp -> return new CSVReader( new InputStreamReader( resp.entity.content , ParserRegistry.getCharset( resp ) ) ) } http.get( uri : 'http://localhost:8080/test/test.csv' , contentType : 'text/csv' ) { resp, csv -> assert csv instanceof CSVReader // parse the csv stream here. }
http://groovy.codehaus.org/modules/http-builder/home.html