「Apache Grooy」- 发送 HTTP 请求 @20210505
问题描述
该笔记将记录:在 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
浙公网安备 33010602011771号