问题描述该笔记将记录:在 Groovy 中,如何发送 HTTP 请求,以及相关问题处理。解决方案通过 Groovy 形式HTTP GETdef html = http://google.com.toURL().texthtml = new URL(http://stackoverflow.com).get...
问题描述
该笔记将记录:在 Groovy 中,如何发送 HTTP 请求,以及相关问题处理。
解决方案
通过 Groovy 形式
HTTP GET
def html = "http://google.com".toURL().text
html = new URL("http://stackoverflow.com").getText()
html = new URL("http://stackoverflow.com").text
// or
new URL("http://stackoverflow.com").getText(
connectTimeout: 5000,
readTimeout: 10000,
useCaches: true,
allowUserInteraction: false,
requestProperties: ['Connection': 'close']
)
HTTP POST
def baseUrl = new URL('http://api.duckduckgo.com')
def queryString = 'q=groovy&format=json&pretty=1'
def connection = baseUrl.openConnection()
connection.with {
doOutput = true
requestMethod = 'POST'
outputStream.withWriter { writer ->
writer << queryString
}
println content.text
}
通过 Java 形式
// GET
def get = new URL("https://httpbin.org/get").openConnection();
def getRC = get.getResponseCode();
println(getRC);
if (getRC.equals(200)) {
println(get.getInputStream().getText());
}
// POST
def post = new URL("https://httpbin.org/post").openConnection();
def message = '{"message":"this is a message"}'
post.setRequestMethod("POST")
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/json")
post.getOutputStream().write(message.getBytes("UTF-8"));
def postRC = post.getResponseCode();
println(postRC);
if (postRC.equals(200)) {
println(post.getInputStream().getText());
}
常见问题处理
URL Encode
import java.net.URLEncoder
def encodedString = URLEncoder.encode("string with spaces and +", "UTF-8")
assert encodedString == "string+with+spaces+and+%2B"
相关文章
「Groovy」- 处理日期时间
「Groovy」- 正则表达式
「Groovy」- 连接数据库(使用 MySQL 演示)
「Apache Groovy」- 连接 SQLite 数据库
「Groovy」- XML
「Groovy」- 常用 JSON 操作(Object 与 JSON)
「Groovy」- 处理路径地址
参考文献
Groovy built-in REST/HTTP client? - Stack Overflow
How to get the REST response in Groovy? - Stack Overflow
Executing an HTTP POST request - Groovy 2 Cookbook
本文标题为:「Apache Grooy」- 发送 HTTP 请求 @20210505
基础教程推荐
- Centos7 nginx的安装以及开机自启动的设置 2023-09-22
- P3 利用Vulnhub复现漏洞 - Apache SSI 远程命令执行漏洞 2023-09-10
- 通过StatefulSet部署有状态服务应用实现方式 2022-10-01
- Centos 安装Django2.1 2023-09-24
- windows环境下apache-apollo服务器搭建 2023-09-10
- Apache CarbonData 1.0.0发布及其新特性介绍 2023-09-11
- Docker容器操作方法详解 2022-11-13
- RFO SIG之openEuler AWS AMI 制作详解 2022-12-28
- Apache Kafka 2.5 稳定版发布,新特性抢先看 2023-09-11
- 为Win2003服务器打造铜墙铁壁的方法步骤 2022-09-01
