前言
- 本篇来学习下使用Groovy发GET和POST请求
GET请求
def resp1 = new URL('https://postman-echo.com/get?name=DaHai&city=Beijing').text
println(resp1)
def resp2 = 'https://postman-echo.com/get?name=DaHai&city=Beijing'.toURL().text
println(resp2)
POST请求
def baseUrl = new URL('https://postman-echo.com/post')
def connection = baseUrl.openConnection()
connection.with {
doOutput = true
requestMethod = 'POST'
addRequestProperty 'Content-Type', 'application/json'
outputStream.withWriter{ it << '{"name": "DaHai", "city": "Beijing"}' }
println content.text
}
- 查看输出