java发送Http请求

使用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());
        }
    }
}
posted @ 2023-04-12 16:14  黑人的乔丹鞋  阅读(127)  评论(0编辑  收藏  举报