前言
- 本篇来学习下使用Groovy发GET和POST请求
GET请求
/* @Time:2023/2/23 @Author: 大海 */ // 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请求
/* @Time:2023/2/23 @Author: 大海 */ // post请求 https://postman-echo.com/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 }
- 查看输出