Groovy新发布的 HTTPBuilder 模块


http://groovy.codehaus.org/modules/http-builder/

HTTPBuilder 是基于 Apache  HttpClient框架的Groovy模块,使用Groovy的语法习惯。request/response的模式是借鉴与Prototype.js Ajax.Request模块的灵感,所以使用非常方便。有了HTTPBuilder 通过Groovy语言实现定向爬虫、模拟浏览器、操作HTTP协议等工作就方便的多了,不用在使用复杂的Connection或者HttpClient了。

 
访问JSON接口的例子:

def http = new HTTPBuilder( 'http://ajax.googleapis.com' )  
  
// perform a GET request, expecting JSON response data  
http.request( GET, JSON ) {  
  url.path = '/ajax/services/search/web'  
  url.query = [ v:'1.0', q: 'Calvin and Hobbes' ]  
  
  headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'  
  
  // response handler for a success response code:  
  response.success = { resp, json ->  
    println resp.statusLine  
  
    // parse the JSON response object:  
    json.responseData.results.each {   
      println "  ${it.titleNoFormatting} : ${it.visibleUrl}"  
    }  
  }  
  
  // handler for any failure status code:  
  response.failure = { resp ->  
    println "Unexpected error: ${resp.statusLine.statusCode} : ${resp.statusLine.reasonPhrase}"   
  }  
} 

 

访问网页,对错误信息的处理

 

import static groovyx.net.http.Method.GET
import static groovyx.net.http.ContentType.TEXT

http.request(GET,TEXT) { req ->
  url.host = 'www.google.com' // overrides default URL
  headers.'User-Agent' = 'Mozilla/5.0'
  
  response.success = { resp, reader ->
    println 'my response handler!'
    assert resp.statusLine.statusCode == 200
    println resp.statusLine
    System.out << reader // print response stream
  }
  
  response.'401' = { resp ->  // fired only for a 401 (access denied) status code
    println 'access denied'
  }

  http.handler.'404' = { resp ->
    println "Page not found"
  }

// Used for all other failure codes not handled by a code-specific handler:
  http.handler.failure = { resp ->
    println "Unexpected failure: ${resp.statusLine}"
  }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值