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;
    }
}
相关推荐
VIP_CQCRE2 天前
AI 子站域名能打开就算上线?一份 DNS、登录与计费验收清单
https·dns·ai应用·网站运维·acedatacloud
我不会插花弄玉3 天前
5.应⽤层协议HTTP【由浅入深-网络】
http
如夏倾城4 天前
QUIC——HTTP/3 的唯一底层传输协议 及 0-RTT恢复
网络·网络协议·tcp/ip·安全·http
略懂而已4 天前
安装SSL后网站速度变慢?
网络·网络协议·ssl
CodeYp20195 天前
第13讲:HTTPS 协议原理
linux·https
Thanks_ks5 天前
HTTPS:浏览器地址栏那把锁的工作原理
http·网络安全·https·tls·加密算法·数字证书·中间人攻击
杨凯凡5 天前
Spring Boot 大文件下载如何实现断点续传?HTTP Range、206 与 416 实战
spring boot·后端·http
FungLeo5 天前
成为全栈·Vue 管理后台篇·用 fetch 建一层可控的请求内核
前端·javascript·vue.js·http·fetch·formdata·接口封装
wuyk5556 天前
Spider-第03讲-HTTP速通与读懂响应
网络·爬虫·网络协议·http
杨凯凡7 天前
Spring Framework 7 HTTP Interface 实战:声明式 RestClient、超时与测试
java·spring·http