build.gradle里面想进行网络请求应该如何操作
get非常的简单
def res1 = new URL('https://httpbin.org/ip').text
// or
def res2 = 'https://httpbin.org/ip'.toURL().text
post可以这么用
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
/**
* 发送 HTTP POST 请求
* @param url 请求的网址
* @param data 请求所需的参数,可选
* @param is_json 请求参数类型是否为 json 格式
* @return Map
*/
def http_post(url, data = null, isJson = false) {
def conn = new URL(url).openConnection()
conn.setRequestMethod("POST")
if (data) {
if (isJson) {
conn.setRequestProperty("Content-Type", "application/json")
data = JsonOutput.toJson(data)
}
// 输出请求参数
conn.doOutput = true
def writer = new OutputStreamWriter(conn.outputStream)
writer.write(data)
writer.flush()
writer.close()
}
if(isJson){
def json = new JsonSlurper()
def result = json.parseText(conn.content.text)
return result
}else {
return conn.content.text
}
}
def res = http_post('https://httpbin.org/post', '{"name": "John", "age": 34}', true)
print("输出")
println(res)
输出结果
输出{args={}, data="{\"name\": \"John\", \"age\": 34}", files={}, form={}, headers={Accept=text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2, Content-Length=35, Content-Type=application/json, Host=httpbin.org, User-Agent=Java/1.8.0_302, X-Amzn-Trace-Id=Root=1-618f4d5c-42749b3b6a0e9bf82acdc6a1}, json={"name": "John", "age": 34}, origin=203.218.243.233, url=https://httpbin.org/post}
|