问题描述该笔记将记录:在 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
- 解决:apache24 安装后闪退和配置端口映射和连接超时设置 2023-09-11
- 【转载】CentOS安装Tomcat 2023-09-24
- KVM虚拟化Linux Bridge环境部署的方法步骤 2023-07-11
- 利用Docker 运行 python 简单程序 2022-10-16
- IIS搭建ftp服务器的详细教程 2022-11-15
- 教你在docker 中搭建 PHP8 + Apache 环境的过程 2022-10-06
- CentOS7安装GlusterFS集群的全过程 2022-10-10
- CentOS_mini下安装docker 之 安装docker CE 2023-09-23
- 阿里云ECS排查CPU数据分析 2022-10-06
- nginx中封禁ip和允许内网ip访问的实现示例 2022-09-23
