https请求跳过证书(post请求)

package com.boc.common.utils.http;


import javax.net.ssl.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpsClientUtils {

    public static void main(String[] args) {
        try {
            String url = "https://ip/LfApi/api/documents";
            System.out.println(url);
            List<String> valueList = new ArrayList<>();
            valueList.add("General");
            valueList.add("Credit File");

            Map<String, Object> propertiesObject = new HashMap<String, Object>();
            propertiesObject.put("Name","Doc1");
            propertiesObject.put("Value",valueList);

            List<Map<String, Object>> propertiesList = new ArrayList<>();
            propertiesList.add(propertiesObject);

            Map<String, Object> documentsObject = new HashMap<String, Object>();
            documentsObject.put("Name","Doc1");
            documentsObject.put("path","/LFRepo/NewCustomer/Customer_ABC");
            documentsObject.put("Properties",propertiesList);
            documentsObject.put("extension","pdf");
            documentsObject.put("Stream","JUVPRgo=");

            List<Map<String, Object>> documentsList = new ArrayList<>();
            documentsList.add(documentsObject);

            Map<String, Object> documents = new HashMap<String, Object>();
            documents.put("documents", documentsList);

            String bodyParams = "{\"documents\":[{\"Name\":\"Doc1\",\"path\":\"\\\\LFRepo\\\\NewCustomer\\\\Customer_ABC\",\"Properties\":[{\"Name\":\"Template\",\"Value\":[\"General\"]},{\"Name\":\"Type\",\"Value\":[\"Credit File\"]},{\"Name\":\"Field 1\",\"Value\":[\"Val_Field1\"]},{\"Name\":\"Field 2\",\"Value\":[\"Val_Field2\"]},{\"Name\":\"Field MV\",\"Value\":[\"Val1-1\",\"Val1-2\"]}],\"extension\":\"pdf\",\"Stream\":\"JUVPRgo=\"},{\"Name\":\"Doc2\",\"path\":\"\\\\LFRepo\\\\NewCustomer\\\\Customer_ABC\",\"Properties\":[{\"Name\":\"Template\",\"Value\":[\"General\"]},{\"Name\":\"Type\",\"Value\":[\"Credit File\"]},{\"Name\":\"Field 1\",\"Value\":[\"Val_Field1\"]},{\"Name\":\"Field 2\",\"Value\":[\"Val_Field2\"]},{\"Name\":\"Field MV\",\"Value\":[\"Val2-1\",\"Val2-2\"]}],\"extension\":\"tif\",\"Stream\":\"JUVPRgo=\"}]}";
            System.out.println(bodyParams);
			String sendPost = sendHttpsPost(url, bodyParams, "utf-8");
			System.out.println(sendPost);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * https请求
     * @param urlParams 请求地址
     * @param bodyParams   body参数
     * @param charset  编码
     * @return
     */
    public static String sendHttpsPost(String urlParams, String bodyParams, String charset) throws Exception {
        HttpsURLConnection con = null;
        OutputStreamWriter osw = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            URL url = new URL(urlParams);
            con = (HttpsURLConnection) url.openConnection();
            // 绕过证书验证
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
            con.setSSLSocketFactory(sc.getSocketFactory());
            // 绕过验证主机名和服务器验证方案的匹配是可接受的
            con.setHostnameVerifier(new CustomizedHostnameVerifier());
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Accept", "application/json");// 响应json字符串
            con.setRequestProperty("Content-Type", "application/json");// 请求body参数为json字符串
            // con.setRequestProperty("Accept", "*/*");
            // con.setRequestProperty("Connection", "keep-alive");
            // con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36");
            if (bodyParams != null) {
                osw = new OutputStreamWriter(con.getOutputStream(), charset);
                osw.write(bodyParams);// 请求参数为json字符串
                osw.flush();
                osw.close();
            }
            is = con.getInputStream();
            baos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int len;
            while ((len = is.read(buf)) != -1) {
                baos.write(buf, 0, len);
                baos.flush();
            }
            return baos.toString(charset);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                if (osw != null) {
                    osw.close();
                }
                if (baos != null) {
                    baos.close();
                }
                if (is != null) {
                    is.close();
                }
                if (con != null) {
                    con.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

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

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

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }
    }
    static class CustomizedHostnameVerifier implements HostnameVerifier {
        // 重写验证方法
        @Override
        public boolean verify(String urlHostName, SSLSession session) {
            // System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
            // 所有都正确
            return true;
        }
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中发送POST请求跳过证书验证,可以使用HttpsURLConnection类的一些方法来实现。以下是一种示例代码,其中使用了TrustManager和HostnameVerifier来跳过证书验证: ```java import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.security.cert.X509Certificate; public class HttpsPost { public static void main(String[] args) throws Exception { String url = "https://example.com/api"; String data = "param1=value1&param2=value2"; // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); // Create all-trusting host name verifier HostnameVerifier allHostsValid = (hostname, session) -> true; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); // Send POST request URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.getOutputStream().write(data.getBytes("UTF-8")); // Get response BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // Print response System.out.println(response.toString()); } } ``` 在上面的代码中,我们创建了一个TrustManager,该TrustManager不验证证书链。然后,我们使用该TrustManager创建了一个SSLContext,并将其设置为默认的SSLSocketFactory。接下来,我们创建了一个HostnameVerifier,该Verifier接受所有主机名,并将其设置为默认的HostnameVerifier。最后,我们使用HttpsURLConnection类来发送POST请求,该请求跳过证书验证。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值