Groovy 操作http请求

这篇博客介绍了如何利用Groovy的HTTP Builder模块来执行HTTP请求,包括GET、POST等操作,支持处理JSON、HTML和CSV格式的数据,并且提到了结合jQuery进行解析的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

话不多说,先上一段代码,如果你使用过jquery,看到这样的代码是不是很亲切呢?
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、 封装请求配置的一个闭包
在请求配置闭包中可以设置请求的相关参数以及对响应的处理闭包,更多详细配置可以参考:
http://groovy.codehaus.org/modules/http-builder/apidocs/groovyx/net/http/HTTPBuilder.RequestConfigDelegate.html

如果在request方法的参数中未设置ContentType参数,默认是使用ContentType.ANY,也就是说具体的文档类型取决于服务器端
指定了这参数后,就会强制按照这个参数来解析响应内容,而不管respone中的Content-Type值,几种常用的类型处理:
TEXT,纯文本
XML,采用XmlSlurper解析内容
HTML,先采用NekoHTML使HTML规范化,之后采用XmlSlurper解析DOM
JSON,采用JSON-lib解析内容

有了上面的粗略了解后,下面再各个细分详解:

1、GET请求
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 }
}

上面的代码发起一个get请求,并对返回的html内容强制以TEXT形式处理
HTTPBuilder提供了一个更简洁的方式发送get请求
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() == 1
2、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指定了提交参数的处理类型,
这里指定使用urlencoder对提交的参数编码处理,若未指定就会使用request方法中指定的响应内容
处理类型,在上面的代码中并未指定响应内容的处理类型,所以就是ContentType.ANY了。在上面delegate
中提供了send()方法同时处理request content-type 和 request data
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格式数据处理;
处理响应内容中的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的验证,REST支持,请参考:

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



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值