post 請求工具類

人间春风意發表於2024-11-07

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;

@Slf4j
public class PostRequestUtils {

    public PostRequestUtils() {
    }

    /**
     * 傳送POST請求並返回結果
     *
     * @param proxyAddress 代理伺服器地址
     * @param proxyPort    代理伺服器埠
     * @param postUrl      請求URL
     * @param data         請求資料
     * @return 返回結果
     * @throws Exception 丟擲異常
     */
    public String sendMsg(String proxyAddress, String proxyPort, String postUrl, String data) throws Exception {
        PrintWriter out = null;
        BufferedReader reader = null;
        String result = null;
        String returnCode = null;

        try {
            if (data != null && !data.isEmpty()) {
                // 建立連線
                URL url = new URL(postUrl);
                // 忽略證書校驗
                ignoreSsl(postUrl);
                // 設定代理
                HttpURLConnection connection = createConnection(url, proxyAddress, proxyPort);

                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setRequestMethod("POST");
                connection.setUseCaches(false);
                connection.setInstanceFollowRedirects(false);
                connection.setRequestProperty("Charset", "UTF-8");
                connection.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
                connection.setRequestProperty("accept", "*/*");
                connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                connection.setRequestProperty("Connection", "Keep-Alive");

                connection.connect();

                // POST請求
                out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8), true);
                out.write(data);
                out.flush();
                out.close();

                // 從HTTP取得返回結果
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                returnCode = parseReturnMsg(sb.toString());
                log.info("介面返回:" + returnCode);
                reader.close();
                // 斷開連線
                connection.disconnect();
            }
        } catch (IOException e) {
            log.error("發生異常: {}", e.getMessage(), e);
        } finally {
            closeQuietly(out);
            closeQuietly(reader);
        }
        return returnCode;
    }

    /**
     * 解析返回的訊息
     *
     * @param jsonData JSON格式的返回資料
     * @return 解析後的結果
     */
    public String parseReturnMsg(String jsonData) {
        try {
            log.info("接收到的JSON資料: {}", jsonData);
            JSONObject jsonObject = JSONObject.parseObject(jsonData);
            JSONObject result = jsonObject.getJSONObject("result");
            return result.getString("code");
        } catch (Exception e) {
            log.error("解析JSON資料時發生異常: {}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 讀取輸入流並返回位元組陣列
     *
     * @param inStream 輸入流
     * @return 位元組陣列
     * @throws Exception 丟擲異常
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            return outStream.toByteArray();
        } finally {
            inStream.close();
        }
    }

    /**
     * 忽略SSL證書校驗
     *
     * @param postUrl 請求URL
     * @throws Exception 丟擲異常
     */
    public static void ignoreSsl(String postUrl) throws Exception {
        HostnameVerifier hv = (url, session) -> {
            log.warn("警告: URL Host: {} vs. {}", url, session.getPeerHost());
            return true;
        };
        trustAllHttpsCertificates();
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }

    /**
     * 信任所有HTTPS證書
     *
     * @throws Exception 丟擲異常
     */
    private static void trustAllHttpsCertificates() throws Exception {
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[]{new miTM()};
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    /**
     * 自定義信任管理器
     */
    static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    }

    /**
     * 向指定URL傳送GET方法的請求
     *
     * @param url 請求URL
     * @return 返回結果
     */
    public static String get(String url) {
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 建立代理伺服器
            InetSocketAddress addr = new InetSocketAddress("10.12.129.9", 8080);
            Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // HTTP代理

            // 不使用代理
            URLConnection connection = realUrl.openConnection();
            // 使用代理
            // URLConnection connection = realUrl.openConnection(proxy);

            // 設定通用的請求屬性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded;");

            // 建立實際的連線
            connection.connect();

            // 讀取URL的響應
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        } catch (Exception e) {
            log.error("發生異常: {}", e.getMessage(), e);
        } finally {
            closeQuietly(in);
        }
        return "";
    }

    /**
     * 關閉PrintWriter,忽略關閉時的異常
     *
     * @param out PrintWriter物件
     */
    private static void closeQuietly(PrintWriter out) {
        if (out != null) {
            try {
                out.close();
            } catch (Exception ignored) {
            }
        }
    }

    /**
     * 關閉BufferedReader,忽略關閉時的異常
     *
     * @param reader BufferedReader物件
     */
    private static void closeQuietly(BufferedReader reader) {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception ignored) {
            }
        }
    }

    /**
     * 建立HTTP連線
     *
     * @param url          請求URL
     * @param proxyAddress 代理伺服器地址
     * @param proxyPort    代理伺服器埠
     * @return HttpURLConnection物件
     * @throws IOException 丟擲IO異常
     */
    private static HttpURLConnection createConnection(URL url, String proxyAddress, String proxyPort) throws IOException {
        if (proxyPort == null || Integer.parseInt(proxyPort) == 0) {
            return (HttpURLConnection) url.openConnection();
        } else {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, Integer.parseInt(proxyPort)));
            return (HttpURLConnection) url.openConnection(proxy);
        }
    }
}

  

相關文章