http与https连接工具类整理

本文介绍了一款用于处理HTTP和HTTPS请求的实用工具类,包括发送GET和POST请求的方法,支持自定义请求头和超时时间,适用于模块化开发和分布式架构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于项目是模块开发的采用的分布式架构 所以各模块之间需要用http连接频繁调用所以整理出来了经常用的httpUtil类

Httputil(用于http连接)

package cn.com.polycis.config.util;

import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

public class HttpUtil {

    /**
     * 发送http请求
     * @param url 请求路径
     * @param param 请求参数
     * @param headers 请求头
     * @param method 请求方法
     * @param timeOut 请求超时时间
     * @return 响应请求的返回结果
     * @throws Exception
     */
    public static String sendHttp(String url, String param, Map<String, String> headers, String method, Integer timeOut) throws Exception {
        System.out.println(headers);
        method = method == null ? "GET" : method;
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";

        if (!StringUtils.isEmpty(param) && "GET".equalsIgnoreCase(method)) {
            url = url + "?" + param;
        }
        URL realUrl = new URL(url);
        URLConnection conn = realUrl.openConnection();
        if (timeOut != null && timeOut > 0) {
            conn.setReadTimeout(timeOut * 1000);
        }
        HttpURLConnection httpURLConnection = (HttpURLConnection) conn;
        httpURLConnection.setRequestMethod(method.toUpperCase());
        for (Map.Entry<String, String> header : headers.entrySet()) {
            httpURLConnection.setRequestProperty(header.getKey(), header.getValue());
        }
        conn.setDoInput(true);
        if (!StringUtils.isEmpty(param) && "POST".equalsIgnoreCase(method)) {
            conn.setDoOutput(true);
            out = new PrintWriter(conn.getOutputStream());

            out.print(param);
            out.flush();
        }

        httpURLConnection.connect();
        in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
        return result;
    }

    /**
     * 通过key=value的方式创建http的请求头
     * @param keyAndValues
     * @return
     */
    public static Map<String, String> createHearder(String... keyAndValues){
        if (keyAndValues == null || keyAndValues.length == 0){
            return new HashMap<String, String>();
        }
        Map<String, String> headers = new HashMap<String, String>();
        String[] split;
        for (String str : keyAndValues){

            split = str.split("=");
            if (split.length != 2){
                continue;
            }
            headers.put(split[0].trim(), split[1].trim());
        }
        return headers;
    }
}

httpsUtil(用于https连接)

package cn.com.polycis.common.utils;

import org.springframework.util.StringUtils;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

/**
 * <p> Date             :2018/1/18 </p>
 * <p> Module           : </p>
 * <p> Description      : </p>
 * <p> Remark           : </p>
 *
 * @author yangdejun
 * @version 1.0
 *          <p>--------------------------------------------------------------</p>
 *          <p>修改历史</p>
 *          <p>    序号    日期    修改人    修改原因    </p>
 *          <p>    1                                     </p>
 */
public class HttpClient {


    public static String sendHttp(String url, String param, Map<String, String> headers, String method, Integer timeOut) throws Exception {
        method = method == null ? "GET" : method;
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";

        if (!StringUtils.isEmpty(param) && "GET".equalsIgnoreCase(method)) {
            url = url + "?" + param;
        }
        URL realUrl = new URL(url);
        URLConnection conn = realUrl.openConnection();
        if (timeOut != null && timeOut > 0) {
            conn.setReadTimeout(timeOut * 1000);
        }
        HttpURLConnection httpURLConnection = (HttpURLConnection) conn;
        httpURLConnection.setRequestMethod(method.toUpperCase());
        for (Map.Entry<String, String> header : headers.entrySet()) {
            httpURLConnection.setRequestProperty(header.getKey(), header.getValue());
        }
        conn.setDoInput(true);
        if (!StringUtils.isEmpty(param) && "POST".equalsIgnoreCase(method)) {
            conn.setDoOutput(true);
            out = new PrintWriter(conn.getOutputStream());

            out.print(param);
            out.flush();
        }

        httpURLConnection.connect();
        in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
        return result;
    }

    public static String[] sendHttps(String url, String param, Map<String, String> headers, String method, Integer timeOut) throws Exception {
        method = method == null ? "GET" : method;
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";

        if (!StringUtils.isEmpty(param) && "GET".equalsIgnoreCase(method)) {
            url = url + "?" + param;
        }

        HttpsURLConnection.setDefaultHostnameVerifier(new HttpClient().new NullHostNameVerifier());
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        URL realUrl = new URL(url);
        URLConnection conn = realUrl.openConnection();
        if (timeOut != null && timeOut > 0) {
            conn.setReadTimeout(timeOut * 1000);
        }
        HttpsURLConnection httpsURLConnection = (HttpsURLConnection) conn;
        httpsURLConnection.setRequestMethod(method.toUpperCase());
        for (Map.Entry<String, String> header : headers.entrySet()) {
            httpsURLConnection.setRequestProperty(header.getKey(), header.getValue());
        }

        conn.setDoInput(true);
        if (!StringUtils.isEmpty(param) && "POST".equalsIgnoreCase(method)) {
            conn.setDoOutput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
        }

        if (!StringUtils.isEmpty(param) && "PUT".equalsIgnoreCase(method)) {
            ((HttpsURLConnection) conn).setRequestMethod("PUT");
            conn.setDoOutput(true);
            out = new PrintWriter(conn.getOutputStream());

            out.print(param);
            out.flush();
        }

        httpsURLConnection.connect();
        try {
            in = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            result = null;
        }
        return new String[]{String.valueOf(httpsURLConnection.getResponseCode()), result};
    }

    public class NullHostNameVerifier implements HostnameVerifier {
        /*
         * (non-Javadoc)
         *
         * @see javax.net.ssl.HostnameVerifier#verify(java.lang.String,
         * javax.net.ssl.SSLSession)
         */
        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            // TODO Auto-generated method stub
            return true;
        }
    }

    static TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // TODO Auto-generated method stub
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // TODO Auto-generated method stub
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }
    }};


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值