使用java 11添加的HttpClient新API發送Http(Https)請求 HTTP客戶端是在Java 11中添加的。它可以用於通過網路請求HTTP資源。它支持 HTTP / 1.1和HTTP / 2(同步和非同步編程模型),將請求和響應主體作為反應流處理,並遵循熟悉的構建器模式。 參考文章: ...
使用java 11添加的HttpClient新API發送Http(Https)請求
HTTP客戶端是在Java 11中添加的。它可以用於通過網路請求HTTP資源。它支持 HTTP / 1.1和HTTP / 2(同步和非同步編程模型),將請求和響應主體作為反應流處理,並遵循熟悉的構建器模式。
參考文章:https://blog.csdn.net/allway2/article/details/112725692
Maven
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
實例代碼
package org.example;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.Serializable;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.*;
public class Main {
private static final TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
private static final HttpClient client;
static {
// 允許不安全SSL連接
final Properties props = System.getProperties();
props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.TRUE.toString());
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new SecureRandom());
// 構建client實例
client = HttpClient.newBuilder()
.sslContext(sslContext)
.build();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new RuntimeException(e);
}
}
/**
* 發送get請求
* @param url url
* @param params path參數
* @return 響應體
*/
public static JSONObject get(String url, Map<String, Object> params) {
// 拼接url
URI uri = disposeUrl(url, params);
// 構造get請求
HttpRequest req = HttpRequest.newBuilder(uri)
.GET()
.build();
try {
// 發送get請求
HttpResponse<String> res = client.send(req, HttpResponse.BodyHandlers.ofString());
return JSONObject.parseObject(res.body());
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}
/**
* 拼接url請求低質
* @param url url
* @param params 參數
* @return 完整url
*/
private static URI disposeUrl(String url, Map<String, Object> params) {
StringBuilder sb = new StringBuilder(url);
if (params == null || params.keySet().size() == 0) return URI.create(url);
Set<String> keys = params.keySet();
sb.append("?");
keys.forEach(key -> sb.append(key).append("=").append(params.get(key)).append("&"));
return URI.create(sb.substring(0, sb.length() - 1));
}
/**
* 發送post請求
* @param url url
* @param data 參數
* @return 響應體
*/
public static JSONObject post(String url, JSONObject data) {
return post(url, null, data);
}
/**
* 發送post請求
* @param url url
* @param params path參數
* @param data 請求體中的參數
* @return 響應體
*/
public static JSONObject post(String url, Map<String, Object> params, JSONObject data) {
// 拼接uri
URI uri = disposeUrl(url, params);
// 構造post請求
HttpRequest req = HttpRequest.newBuilder(uri)
.POST(HttpRequest.BodyPublishers.ofString(data.toString()))
.build();
try {
// 發送post請求
HttpResponse<String> res = client.send(req, HttpResponse.BodyHandlers.ofString());
return JSONObject.parseObject(res.body());
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}
public static class keyValueRecord implements Serializable {
private String key;
private String value;
public keyValueRecord(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public static void main(String[] args) {
// 獲取token
Map<String, Object> params = new HashMap<>();
params.put("corpid", "xxx");
params.put("corpsecret", "xxx");
JSONObject json = get("https://qyapi.weixin.qq.com/cgi-bin/gettoken", params);
String access_token = json.getString("access_token");
// 獲取審批單號
JSONObject data = new JSONObject();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.add(Calendar.DATE, -15);
data.put("starttime", String.valueOf(cal.getTime().getTime() / 1000));
data.put("endtime", String.valueOf(System.currentTimeMillis() / 1000));
data.put("cursor", 0);
data.put("size", 100);
JSONArray arr = new JSONArray();
arr.add(0, new keyValueRecord("sp_status", "1"));
arr.add(0, new keyValueRecord("template_id", "1970325103043160_1688851905330597_909052414_1534723908"));
data.put("filters", arr);
params = new HashMap<>();
params.put("access_token", access_token);
json = post("https://qyapi.weixin.qq.com/cgi-bin/oa/getapprovalinfo", params, data);
JSONArray list = json.getJSONArray("sp_no_list");
// 獲取審批單詳細信息
for (int i = 0; i < list.size(); i++) {
String item = list.getString(i);
data = new JSONObject();
data.put("sp_no",item);
json = post("https://qyapi.weixin.qq.com/cgi-bin/oa/getapprovaldetail", params, data);
System.out.println(json.toString());
}
}
}