自定义http工具类

自定义HTTP工具类

概述

HttpUtils是一个通用的 HTTP 请求工具类,提供了多种 HTTP 请求方法,包括 GET、POST、SSL 请求以及基于 OkHttp 的请求。该类封装了常见的 HTTP 操作,简化了开发人员在项目中发起 HTTP 请求的过程。


类结构与功能

1. 基础配置

java 复制代码
private static int connectionTimeout = 30 * 1000; // 默认连接超时时间(毫秒)
private static int readTimeout = 300 * 1000;     // 默认读取超时时间(毫秒)
  • 作用:定义默认的连接和读取超时时间。
  • 说明:可以通过方法参数自定义超时时间。

2. GET 请求方法

方法签名
java 复制代码
public static String sendGet(String url)
public static String sendGet(String url, String param)
public static String sendGet(String url, String param, Map<String, String> headParam)
public static String sendGet(String url, String param, String contentType)
public static String sendGet(String url, String param, String contentType, Map<String, String> headParams)
功能说明
  • 支持带参数和请求头的 GET 请求。
  • 自动拼接查询参数到 URL 中。
  • 可自定义编码类型和请求头。
示例代码
java 复制代码
String result = HttpUtils.sendGet("https://example.com/api", "name=John&age=25");
System.out.println(result);

3. POST 请求方法

方法签名
java 复制代码
public static String sendPost(String url, String param)
public static String sendPost(String url, String param, Map<String, String> headParams)
功能说明
  • 支持带参数和请求头的 POST 请求。
  • 默认 Content-Type 为 application/json
  • 参数通过输出流发送至服务器。
示例代码
java 复制代码
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer token");

String result = HttpUtils.sendPost("https://example.com/api", "{\"name\":\"John\"}", headers);
System.out.println(result);

4. SSL 请求方法

方法签名
java 复制代码
public static String sendSSLGet(String url, String param, String contentType, Map<String, String> headParams)
public static String sendSSLPost(String url, String param, Map<String, String> headParams)
功能说明
  • 支持 HTTPS 请求,并跳过 SSL 证书验证。
  • 适用于测试环境或自签名证书场景。
注意事项
  • 生产环境中应避免跳过 SSL 验证,建议使用合法证书。
示例代码
java 复制代码
String result = HttpUtils.sendSSLGet("https://secure.example.com/api", "id=123", "UTF-8", null);
System.out.println(result);

5. 自定义超时时间的方法

方法签名
java 复制代码
public static String sendGetWithTimeOut(String url, String param, String contentType, Map<String, String> headParams, int connectionTimeout, int readTimeout)
public static String sendPostWithTimeout(String url, String param, Map<String, String> headParams, int connectionTimeout, int readTimeout)
功能说明
  • 允许动态设置连接和读取超时时间。
  • 提高灵活性,适应不同网络环境的需求。
示例代码
java 复制代码
int connectTimeout = 5000; // 5 秒
int readTimeout = 10000;   // 10 秒

String result = HttpUtils.sendGetWithTimeOut("https://example.com/api", "data=test", "UTF-8", null, connectTimeout, readTimeout);
System.out.println(result);

6. OkHttp 封装方法

方法签名
java 复制代码
public static String sendOkHttp(String url, String methodType, Map<String, String> headParams, String param)
public static String sendOkHttpWithTimeout(String url, String methodType, Map<String, String> headParams, String param, int connectTimeout, int readTimeout)
功能说明
  • 基于 OkHttp 实现 HTTP 请求。
  • 支持 GET、POST 和 PUT 方法。
  • 可自定义超时时间和请求头。
示例代码
java 复制代码
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");

String result = HttpUtils.sendOkHttp("https://example.com/api", "POST", headers, "{\"message\":\"Hello World\"}");
System.out.println(result);

异常处理机制

异常捕获

所有方法均对以下异常进行了统一处理:

  • ConnectException:网络连接失败。
  • SocketTimeoutException:请求超时。
  • IOException:输入输出错误。
  • Exception:其他未预期异常。

错误返回值

当发生异常时,会返回 JSON 格式的错误信息:

json 复制代码
{
  "code": "error",
  "msg": "具体错误信息"
}

日志记录

日志级别

  • 使用 SLF4J 记录日志。
  • 包含请求地址、参数、响应结果等关键信息。

示例日志

复制代码
INFO  HttpUtils - sendGet - https://example.com/api?name=John
INFO  HttpUtils - recv - {"status":"success","data":"..."}
ERROR HttpUtils - 调用HttpUtils.sendGet ConnectException, url=https://example.com/api,param=name=John

总结

HttpUtils 工具类具有以下特点:

  1. 功能全面:支持 GET、POST、SSL、OkHttp 等多种请求方式。
  2. 易于扩展:可通过参数灵活调整行为。
  3. 健壮性强:完善的异常处理和日志记录机制。
  4. 性能优化:支持自定义超时时间,提升网络请求效率。

该工具类适合在企业级 Java 应用中广泛使用,能够显著降低 HTTP 请求的开发成本。

代码展示

java 复制代码
package com.leo.llos.common.utils.http;

import com.leo.llos.common.constant.Constants;
import com.leo.llos.common.constant.LlosConstants;
import com.leo.llos.common.exception.ServiceException;
import com.leo.llos.common.utils.StringUtils;
import com.leo.llos.common.utils.llos.LlosJsonUtil;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.*;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 通用http发送方法
 *
 * @author ruoyi
 */
public class HttpUtils {

    /**
     * 连接超时时间,单位为毫秒
     */
    private static int connectionTimeout = 30 * 1000;
    /**
     * 读取超时时间
     */
    private static int readTimeout = 300 * 1000;

    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    public static String sendGet(String url) {
        return sendGet(url, StringUtils.EMPTY);
    }

    public static String sendGet(String url, String param) {
        return sendGet(url, param, Constants.UTF8);
    }

    public static String sendGet(String url, String param, Map<String, String> headParam) {
        return sendGet(url, param, Constants.UTF8, headParam);
    }

    public static String sendGet(String url, String param, String contentType) {
        return sendGet(url, param, contentType, null);
    }


    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url         发送请求的 URL
     * @param param       请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @param contentType 编码类型
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param, String contentType, Map<String, String> headParams) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url;
            log.info("sendGet - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setConnectTimeout(connectionTimeout);
            connection.setReadTimeout(readTimeout);
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            if (StringUtils.isNotEmpty(headParams)) {
                headParams.forEach((key, value) -> {
                    connection.setRequestProperty(key, value);
                });
            }
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error("请求失败,请检查网络是否正常!").toJSONString());
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error(e.getMessage()).toJSONString());
        } catch (IOException e) {
            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error(e.getMessage()).toJSONString());
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error(e.getMessage()).toJSONString());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
                result = new StringBuilder(LlosJsonUtil.error(ex.getMessage()).toJSONString());
            }
        }
        return result.toString();
    }

    public static String sendGetWithTimeOut(String url,
                                            String param,
                                            String contentType,
                                            Map<String, String> headParams,
                                            int connectionTimeout, int readTimeout) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url;
            log.info("sendGet - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            //毫秒
            connection.setConnectTimeout(connectionTimeout);
            connection.setReadTimeout(readTimeout);
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            if (StringUtils.isNotEmpty(headParams)) {
                headParams.forEach((key, value) -> {
                    connection.setRequestProperty(key, value);
                });
            }
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error("请求失败,请检查网络是否正常!").toJSONString());
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error(e.getMessage()).toJSONString());
        } catch (IOException e) {
            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error(e.getMessage()).toJSONString());
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error(e.getMessage()).toJSONString());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
                result = new StringBuilder(LlosJsonUtil.error(ex.getMessage()).toJSONString());
            }
        }
        return result.toString();
    }


    public static String sendPost(String url, String param) {
        return sendPost(url, param, null);
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param, Map<String, String> headParams) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            log.info("sendPost - {} 入参-{} 请求头-{}", url, param, headParams);
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setConnectTimeout(connectionTimeout);
            conn.setReadTimeout(readTimeout);
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Content-Type", "application/json");
            if (StringUtils.isNotEmpty(headParams)) {
                headParams.forEach((key, value) -> {
                    conn.setRequestProperty(key, value);
                });
            }
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error("请求失败,请检查网络是否正常!").toJSONString());
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error(e.getMessage()).toJSONString());
        } catch (IOException e) {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error(e.getMessage()).toJSONString());
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error(e.getMessage()).toJSONString());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
                result = new StringBuilder(LlosJsonUtil.error(ex.getMessage()).toJSONString());
            }
        }
        return result.toString();
    }

    public static String sendPostWithTimeout(String url,
                                             String param,
                                             Map<String, String> headParams,
                                             int connectionTimeout, int readTimeout) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            log.info("sendPost - {} 入参-{} 请求头-{}", url, param, headParams);
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            //毫秒
            conn.setConnectTimeout(connectionTimeout);
            conn.setReadTimeout(readTimeout);
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Content-Type", "application/json");
            if (StringUtils.isNotEmpty(headParams)) {
                headParams.forEach((key, value) -> {
                    conn.setRequestProperty(key, value);
                });
            }
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error("请求失败,请检查网络是否正常!").toJSONString());
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error(e.getMessage()).toJSONString());
        } catch (IOException e) {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error(e.getMessage()).toJSONString());
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error(e.getMessage()).toJSONString());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
                result = new StringBuilder(LlosJsonUtil.error(ex.getMessage()).toJSONString());
            }
        }
        return result.toString();
    }


    public static String sendSSLGet(String url, String param, String contentType, Map<String, String> headParams) {
        StringBuilder result = new StringBuilder();
        String urlNameString = url + "?" + param;
        BufferedReader in = null;
        try {
            log.info("sendSSLGet - {}", urlNameString);

            // 创建一个信任所有证书的 TrustManager
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            }};

            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());

            URL console = new URL(urlNameString);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            conn.setConnectTimeout(connectionTimeout);
            conn.setReadTimeout(readTimeout);
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Content-Type", "application/json");
            if (StringUtils.isNotEmpty(headParams)) {
                headParams.forEach((key, value) -> {
                    conn.setRequestProperty(key, value);
                });
            }
            conn.setDoOutput(true);
            conn.setDoInput(true);

            // 设置跳过 SSL 验证
            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnamllosrifier((hostname, session) -> true);

            conn.connect();
            InputStream is = conn.getInputStream();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
            log.info("recv - {}", result);
            conn.disconnect();
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendSSLGet ConnectException, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error(e.getMessage()).toJSONString());
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendSSLGet SocketTimeoutException, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error(e.getMessage()).toJSONString());
        } catch (IOException e) {
            log.error("调用HttpUtils.sendSSLGet IOException, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error(e.getMessage()).toJSONString());
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendSSLGet Exception, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error(e.getMessage()).toJSONString());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
                result = new StringBuilder(LlosJsonUtil.error(ex.getMessage()).toJSONString());
            }
        }
        return result.toString();
    }

    public static String sendSSLPost(String url, String param, Map<String, String> headParams) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            log.info("sendSSLPost - {}", url);

            // 创建一个信任所有证书的 TrustManager
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            }};

            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());

            URL realUrl = new URL(url);
            HttpsURLConnection conn = (HttpsURLConnection) realUrl.openConnection();
            conn.setConnectTimeout(connectionTimeout);
            conn.setReadTimeout(readTimeout);
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Content-Type", "application/json");
            if (StringUtils.isNotEmpty(headParams)) {
                headParams.forEach((key, value) -> {
                    conn.setRequestProperty(key, value);
                });
            }
            conn.setDoOutput(true);
            conn.setDoInput(true);

            // 设置跳过 SSL 验证
            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnamllosrifier((hostname, session) -> true);

            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error(e.getMessage()).toJSONString());
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error(e.getMessage()).toJSONString());
        } catch (IOException e) {
            log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error(e.getMessage()).toJSONString());
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
            result = new StringBuilder(LlosJsonUtil.error(e.getMessage()).toJSONString());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
                result = new StringBuilder(LlosJsonUtil.error(ex.getMessage()).toJSONString());
            }
        }
        return result.toString();
    }


    private static class TrustAnyTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }

    private static class TrustAnyHostnamllosrifier implements Hostnamllosrifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }


    /**
     * 使用okHttp请求
     *
     * @param url        请求url
     * @param methodType GET/POST
     * @param headParams 请求头
     * @param param      请求参数
     * @return
     */
    public static String sendOkHttp(String url, String methodType, Map<String, String> headParams, String param) {
        String result = null;
        if (!StringUtils.isEqualsStringList(methodType, llosConstants.METHOD_GET, llosConstants.METHOD_POST)) {
            throw new ServiceException("common.httpUtils.error1","methodType异常,不为GET/POST"); //i18n-patched
        }
        try {
            String contentType = "application/json";
            if (headParams != null && headParams.get("Content-Type") != null) {
                contentType = headParams.get("Content-Type").toString();
            }
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            Request.Builder builder = new Request.Builder()
                    .url(url);
            MediaType mediaType = MediaType.parse(contentType);
            if (StringUtils.isNotEmpty(param)) {
                if (StringUtils.isEquals(methodType, llosConstants.METHOD_GET)) {
                    url = url + "?" + param;
                } else if (StringUtils.isEquals(methodType, llosConstants.METHOD_POST)) {
                    RequestBody body = RequestBody.create(mediaType, param);
                    builder.method(methodType, body);
                } else if (StringUtils.isEquals(methodType, llosConstants.METHOD_PUT)) {
                    RequestBody body = RequestBody.create(mediaType, param);
                    builder.method(methodType, body);
                }
            }
            if (StringUtils.isNotEmpty(headParams)) {
                headParams.forEach((key, value) -> {
                    builder.addHeader(key, value);
                });
            }
            Request request = builder.build();
            Response response = client.newCall(request).execute();
            result = response.body().string();

        } catch (Exception e) {
            log.error("调用HttpUtils.sendOkHttp Exception, url=" + url + ",param=" + param, e);
            result = LlosJsonUtil.error(e.getMessage()).toJSONString();
        }
        return result;
    }

    /**
     * 使用okHttp请求,可自定义超时时间
     *
     * @param url           请求url
     * @param methodType    GET/POST
     * @param headParams    请求头
     * @param param         请求参数
     * @param connectTimeout 连接超时时间(秒)
     * @param readTimeout    读取超时时间(秒)
     * @return
     */
    public static String sendOkHttpWithTimeout(String url,
                                               String methodType,
                                               Map<String, String> headParams,
                                               String param,
                                               int connectTimeout, int readTimeout) {
        String result = null;
        if (!StringUtils.isEqualsStringList(methodType, llosConstants.METHOD_GET, llosConstants.METHOD_POST)) {
            throw new ServiceException("common.httpUtils.error1", "methodType异常,不为GET/POST"); //i18n-patched
        }
        try {
            String contentType = "application/json";
            if (headParams != null && headParams.get("Content-Type") != null) {
                contentType = headParams.get("Content-Type").toString();
            }

            // 设置自定义超时时间
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
                    .readTimeout(readTimeout, TimeUnit.MILLISECONDS)
                    .build();

            Request.Builder builder = new Request.Builder()
                    .url(url);
            MediaType mediaType = MediaType.parse(contentType);
            if (StringUtils.isNotEmpty(param)) {
                if (StringUtils.isEquals(methodType, llosConstants.METHOD_GET)) {
                    url = url + "?" + param;
                    builder.url(url);
                } else if (StringUtils.isEquals(methodType, llosConstants.METHOD_POST)) {
                    RequestBody body = RequestBody.create(mediaType, param);
                    builder.method(methodType, body);
                } else if (StringUtils.isEquals(methodType, llosConstants.METHOD_PUT)) {
                    RequestBody body = RequestBody.create(mediaType, param);
                    builder.method(methodType, body);
                }
            }
            if (StringUtils.isNotEmpty(headParams)) {
                headParams.forEach((key, value) -> {
                    builder.addHeader(key, value);
                });
            }
            Request request = builder.build();
            Response response = client.newCall(request).execute();
            result = response.body().string();

        } catch (Exception e) {
            log.error("调用HttpUtils.sendOkHttpWithTimeout Exception, url=" + url + ",param=" + param, e);
            result = LlosJsonUtil.error(e.getMessage()).toJSONString();
        }
        return result;
    }

}
相关推荐
安科士andxe9 小时前
深入解析|安科士1.25G CWDM SFP光模块核心技术,破解中长距离传输痛点
服务器·网络·5g
YJlio12 小时前
1.7 通过 Sysinternals Live 在线运行工具:不下载也能用的“云端工具箱”
c语言·网络·python·数码相机·ios·django·iphone
CTRA王大大12 小时前
【网络】FRP实战之frpc全套配置 - fnos飞牛os内网穿透(全网最通俗易懂)
网络
testpassportcn13 小时前
AWS DOP-C02 認證完整解析|AWS DevOps Engineer Professional 考試
网络·学习·改行学it
通信大师14 小时前
深度解析PCC策略计费控制:核心网产品与应用价值
运维·服务器·网络·5g
Tony Bai15 小时前
告别 Flaky Tests:Go 官方拟引入 testing/nettest,重塑内存网络测试标准
开发语言·网络·后端·golang·php
消失的旧时光-194315 小时前
从 0 开始理解 RPC —— 后端工程师扫盲版
网络·网络协议·rpc
叫我龙翔16 小时前
【计网】从零开始掌握序列化 --- JSON实现协议 + 设计 传输\会话\应用 三层结构
服务器·网络·c++·json
“αβ”16 小时前
网络层协议 -- ICMP协议
linux·服务器·网络·网络协议·icmp·traceroute·ping