Apache Grooy │ 发送 HTTP 请求

郎慎之
2023-12-01

原文地址:Apache Grooy │ 发送 HTTP 请求(永久地址,保存网址不迷路 )

问题描述

该笔记将记录:在 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"

禁止 SSL 校验

import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = [ new X509TrustManager() {
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return null;
    }
    public void checkClientTrusted(X509Certificate[] certs, String authType) {
    }
    public void checkServerTrusted(X509Certificate[] certs, String authType) {
    }
}];

// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
};

// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);


// 接下来,我们就能放心请求 SSL 地址:
def pageContent = "https://insecure.ssl.com".toUrl().text

相关文章

「Apache Groovy」- Grape,依赖管理工具(学习笔记)
「Groovy」- 操作 HTML 文档
「Apache Grooy」- 常用 YAML 操作
「Groovy」- 处理路径地址
「Groovy」- XML
「Groovy」- 常用文件操作
「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
Java/Groovy disable SSL verification

 类似资料: