https/http访问接口工具类,附带ssl忽略证书验证,以及head头部的添加-java版

复制即用

java 复制代码
package utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.X509Certificate;
import java.util.List;

/**
 * @author lpx
 * @create 2021-06-28 11:17
 * @Description http请求工具类
 * @Version 1.0
 */

@Slf4j
@Component
public class HttpSendUtils {


    public static String sendHeaderPostWb(String url, String contentType, String param, List<String> headers) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        HttpURLConnection conn = null;
        try {
            URL realUrl = new URL(url);
            boolean isHttps = "https".equalsIgnoreCase(realUrl.getProtocol());
            if (isHttps) {
                // 创建一个忽略证书验证的SSLContext
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, new X509TrustManager[]{new X509TrustManager() {
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }
                }}, new java.security.SecureRandom());

                // 安装所有的信任管理器(仅用于HTTPS)
                // 注意:在实际应用中,不建议这样做,因为它会绕过SSL/TLS的安全验证。
                // 这里只是为了演示如何忽略证书验证。
                SSLContext.setDefault(sslContext);
                // 创建一个HttpsURLConnection对象
                HostnameVerifier hv = new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true; // 接受任何主机名
                    }
                };
                conn = (HttpsURLConnection) realUrl.openConnection();
                ((HttpsURLConnection) conn).setHostnameVerifier(hv);
            }else{
                conn = (HttpURLConnection) realUrl.openConnection();
            }
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type", contentType);
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            if (!headers.isEmpty()) {
                for (String header : headers) {
                    String[] parts = header.split(":");
                    conn.setRequestProperty(parts[0].trim(), parts[1].trim());
                }
            }
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();

            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        return result;
    }
}
相关推荐
布莱克60512 小时前
HTTP 状态码详解:从分类到实战
计算机网络·http·状态码
StevenSurpass14 小时前
打印业务彻底解耦:FastPrintAgent 统一 JSON 模型 + FastReport 引擎的设计与落地
mqtt·http·中间件·打印·fastreport
JamesShi16816 小时前
华为云证书续费操作全流程,针对购买华为云企业门户建站的用户!
ssl
2601_9670195116 小时前
SSL 证书不止加密,还影响网站信任与 SEO
ssl
小此方2 天前
Linux网络(十二):HTTP短连接与长连接:从Connection机制到Cookie、Session,彻底理解HTTP的无状态
服务器·网络·http
江畔柳前堤2 天前
On-Policy Distillation 全景深潜
人工智能·网络协议·目标检测·http·机器学习·chatgpt·重构
2601_967019512 天前
证书兼容性排查:SSL 部署后浏览器不安全告警分析
ssl
2501_915909062 天前
怎么用 FlutterFlow 把应用发布到 App Store?
android·ios·小程序·https·uni-app·iphone·webview
157092511342 天前
Android进阶之光:HTTP协议原理深度解析
android·网络协议·http
2501_916008892 天前
全平台抓包工具,Windows、iPhone、Linux三个平台抓包测试
网络协议·计算机网络·网络安全·ios·adb·https·udp