zhaowenxuan
8 天以前 db52209b0d830d00c7ec807e2b66d94079d4aff6
ltkj-admin/src/main/java/com/ltkj/web/wxUtils/HttpClientUtils.java
@@ -1,6 +1,8 @@
package com.ltkj.web.wxUtils;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
@@ -21,19 +23,24 @@
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
 * httpClient 工具类
 *
 * @create 2019-02-10 下午 2:49
 */
@Component
@Slf4j
public class HttpClientUtils {
    /**
@@ -46,20 +53,24 @@
    /**
     * 静态内部类---作用:单例产生类的实例
     * @author Administrator
     *
     * @author Administrator
     */
    private static class LazyHolder {
        private static final HttpClientUtils INSTANCE = new HttpClientUtils();
    }
    HttpClientUtils(){}
    public static HttpClientUtils getInstance(){
    HttpClientUtils() {
    }
    public static HttpClientUtils getInstance() {
        return LazyHolder.INSTANCE;
    }
    /**
     * 发送 post请求
     *
     * @param httpUrl 地址
     */
    public String sendHttpPost(String httpUrl) {
@@ -69,8 +80,9 @@
    /**
     * 发送 post请求
     *
     * @param httpUrl 地址
     * @param params 参数(格式:key1=value1&key2=value2)
     * @param params  参数(格式:key1=value1&key2=value2)
     */
    public String sendHttpPost(String httpUrl, String params) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
@@ -85,10 +97,232 @@
        return sendHttpPost(httpPost);
    }
    public static String sendPost(String httpUrl, Map<String, Object> maps) {
        try {
            // 1. 创建 URL 对象
            URL url = new URL(httpUrl);
            // 2. 创建 HttpURLConnection 对象
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 3. 设置请求方法为 POST
            connection.setRequestMethod("POST");
            // 4. 设置 Content-Type 头部字段
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            // 6. 向服务器发送数据
            String requestBody = JSONUtil.toJsonStr(maps);
            log.info(httpUrl+"入参:   "+requestBody);
//            String requestBody1 = maps.toString();
            byte[] postData = requestBody.getBytes("UTF-8");
            connection.setDoOutput(true);
            try (OutputStream outputStream = connection.getOutputStream()) {
                outputStream.write(postData);
            }
            // 8. 获取响应数据
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                log.info("=====================================================");
                log.info(httpUrl+"出参");
                log.info(response.toString());
                connection.disconnect();
                return response.toString();
            }
        } catch (IOException e) {
            log.error(String.valueOf(e));
        }
        return null;
    }
    public static String sendPostToken(String httpUrl, Map<String, Object> maps,String authorization) {
        try {
            // 1. 创建 URL 对象
            URL url = new URL(httpUrl);
            // 2. 创建 HttpURLConnection 对象
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 3. 设置请求方法为 POST
            connection.setRequestMethod("POST");
            // 4. 设置 Content-Type 头部字段
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            connection.setRequestProperty("Authorization", authorization);
            // 6. 向服务器发送数据
            String requestBody = JSONUtil.toJsonStr(maps);
            log.info(httpUrl+"入参:   "+requestBody);
//            String requestBody1 = maps.toString();
            byte[] postData = requestBody.getBytes("UTF-8");
            connection.setDoOutput(true);
            try (OutputStream outputStream = connection.getOutputStream()) {
                outputStream.write(postData);
            }
            // 8. 获取响应数据
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                log.info("=====================================================");
                log.info(httpUrl+"出参");
                log.info(response.toString());
                connection.disconnect();
                return response.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String sendPostTokenFormUrlencoded(String httpUrl, Map<String, Object> maps, String authorization) {
        HttpURLConnection connection = null;
        OutputStreamWriter writer = null;
        BufferedReader reader = null;
        StringBuilder response = new StringBuilder();
        try {
            // 创建 URL 对象
            URL url = new URL(httpUrl);
            // 打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为 POST
            connection.setRequestMethod("POST");
            // 设置请求头 Content-Type 为 application/x-www-form-urlencoded
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 如果需要 Authorization Header
            if (authorization != null && !authorization.isEmpty()) {
                connection.setRequestProperty("Authorization", authorization);
            }
            // 设置允许输出
            connection.setDoOutput(true);
            // 构建表单数据
            StringBuilder postData = new StringBuilder();
            for (Map.Entry<String, Object> entry : maps.entrySet()) {
                if (postData.length() > 0) {
                    postData.append("&");
                }
                postData.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
                        .append("=")
                        .append(URLEncoder.encode(entry.getValue().toString(), "UTF-8"));
            }
            // 获取输出流并写入表单数据
            writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(postData.toString());
            writer.flush();
            // 获取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭流
            try {
                if (writer != null) writer.close();
                if (reader != null) reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return response.toString();
    }
    public static String sendPostTokenFormData(String httpUrl, Map<String, Object> maps, String authorization) {
        HttpURLConnection connection = null;
        DataOutputStream outStream = null;
        BufferedReader reader = null;
        StringBuilder response = new StringBuilder();
        // 边界字符串
        String boundary = "----WebKitFormBoundary" + UUID.randomUUID().toString().replaceAll("-", "");
        String CRLF = "\r\n"; // 换行符
        try {
            // 创建 URL 对象
            URL url = new URL(httpUrl);
            // 打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为 POST
            connection.setRequestMethod("POST");
            // 设置请求头 Content-Type 为 multipart/form-data
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            // 如果需要 Authorization Header
            if (authorization != null && !authorization.isEmpty()) {
                connection.setRequestProperty("Authorization", authorization);
            }
            // 设置允许输出
            connection.setDoOutput(true);
            // 获取输出流
            outStream = new DataOutputStream(connection.getOutputStream());
            // 遍历传入的表单数据,并按照 multipart/form-data 格式写入
            for (Map.Entry<String, Object> entry : maps.entrySet()) {
                outStream.writeBytes("--" + boundary + CRLF);
                outStream.writeBytes("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + CRLF);
                outStream.writeBytes("Content-Type: text/plain; charset=UTF-8" + CRLF);
                outStream.writeBytes(CRLF);  // 这里是分隔符,空一行
                outStream.writeBytes(entry.getValue().toString() + CRLF);
            }
            // 结束 multipart/form-data 发送数据部分
            outStream.writeBytes("--" + boundary + "--" + CRLF);
            // 刷新输出流
            outStream.flush();
            // 获取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭流
            try {
                if (outStream != null) outStream.close();
                if (reader != null) reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return response.toString();
    }
    /**
     * 发送 post请求
     *
     * @param httpUrl 地址
     * @param maps 参数
     * @param maps    参数
     */
    public String sendHttpPost(String httpUrl, Map<String, String> maps) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
@@ -105,8 +339,10 @@
        return sendHttpPost(httpPost);
    }
    /**
     * 发送Post请求
     *
     * @param httpPost
     * @return
     */
@@ -123,12 +359,12 @@
            long execStart = System.currentTimeMillis();
            response = httpClient.execute(httpPost);
            long execEnd = System.currentTimeMillis();
            System.out.println("=================执行post请求耗时:"+(execEnd-execStart)+"ms");
            System.out.println("=================执行post请求耗时:" + (execEnd - execStart) + "ms");
            long getStart = System.currentTimeMillis();
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
            long getEnd = System.currentTimeMillis();
            System.out.println("=================获取响应结果耗时:"+(getEnd-getStart)+"ms");
            System.out.println("=================获取响应结果耗时:" + (getEnd - getStart) + "ms");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
@@ -149,6 +385,7 @@
    /**
     * 发送 get请求
     *
     * @param httpUrl
     */
    public String sendHttpGet(String httpUrl) {
@@ -158,6 +395,7 @@
    /**
     * 发送 get请求Https
     *
     * @param httpUrl
     */
    public String sendHttpsGet(String httpUrl) {
@@ -167,6 +405,7 @@
    /**
     * 发送Get请求
     *
     * @param httpGet
     * @return
     */
@@ -206,10 +445,11 @@
    /**
     * 发送Get请求Https
     *
     * @param httpGet
     * @return
     */
    private String sendHttpsGet(HttpGet httpGet) {
    public String sendHttpsGet(HttpGet httpGet) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
@@ -244,6 +484,7 @@
    /**
     * 发送xml数据
     *
     * @param url
     * @param xmlData
     * @return
@@ -286,4 +527,49 @@
    }
    public static String sendPost(String httpUrl, Map<String, Object> maps,String token) {
        try {
            // 1. 创建 URL 对象
            URL url = new URL(httpUrl);
            // 2. 创建 HttpURLConnection 对象
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 3. 设置请求方法为 POST
            connection.setRequestMethod("POST");
            // 4. 设置 Content-Type 头部字段
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            //设置请求token
            connection.setRequestProperty("Authorization",token);
            // 6. 向服务器发送数据
            String requestBody = JSONUtil.toJsonStr(maps);
            log.info(httpUrl+"入参:   "+requestBody);
//            String requestBody1 = maps.toString();
            byte[] postData = requestBody.getBytes("UTF-8");
            connection.setDoOutput(true);
            try (OutputStream outputStream = connection.getOutputStream()) {
                outputStream.write(postData);
            }
            // 8. 获取响应数据
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                log.info("=====================================================");
                log.info(httpUrl+"出参");
                log.info(response.toString());
                connection.disconnect();
                return response.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}