前阵子有一个需求,持续集成平台需要获取一个文件列表,并以可选择参数的方式列出来。列表文件来自于一个web页面,下面挂在了N个可选的文件(build后生成的zip包)
考虑用groovy发送http请求获取response,解析后以列表方式展示,因为groovy是新手,所以走了很多弯路。
1. 首先groovy请求http需要依赖HTTPBuilder模块儿,不知道怎么安装模块儿,辗转了半天,后来发现支持Grab语法,代码如下
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7' )
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.RESTClient
import groovyx.net.http.HttpResponseDecorator
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
def http = new HTTPBuilder()
http.request( 'http://10.1.90.42', GET, TEXT ) {
req ->
uri.path = '/android_test/releases/test'
headers.'User-Agent' = "Mozilla/5.0 Firefox/3.0.4"
headers.Accept = 'application/json'
response.success = {
resp, reader ->
assert resp.statusLine.statusCode == 200
println "Got response: ${resp.statusLine}"
println "Content-Type: ${resp.headers.'Content-Type'}"
println reader.text
}
response.'404' = {
println 'Not found'
}
}
2. 也可以用另一个http请求方式,不用安装module
def connection = new URL("http://10.1.30.42/android_test/releases/test").openConnection()
connection.setRequestMethod('GET')
connection.doOutput = true
def writer = new OutputStreamWriter(connection.outputStream)
writer.flush()
writer.close()
connection.connect()
def respText = connection.content.text