java发送https忽略证书

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
     * 发送post请求
     * @param urlStr
     * @param param
     * @return
     */
    public static String doPostReq(String urlStr,String param){
        String result = "";
        BufferedReader bufferedReader = null;
        InputStream inputStream = null;
        try {
            trustAllHosts();
            URL url = new URL(urlStr);
            //HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            HttpURLConnection conn = null;
            // 通过请求地址判断请求类型(http或者是https)
            if (url.getProtocol().toLowerCase().equals("https")) {
                HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                https.setHostnameVerifier(DO_NOT_VERIFY);
                conn = https;
            } else {
                conn = (HttpURLConnection) url.openConnection();
            }
            conn.setRequestMethod("POST");//设置请求方式
            conn.setConnectTimeout(15000);//设置连接超时时间
            conn.setReadTimeout(60000);//设置读取远程超时时间
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-type","application/json; charset=utf-8");
            conn.setRequestProperty("Accept",
                    "text/xml,text/javascript,text/html,application/json");
            OutputStream outputStream = conn.getOutputStream();//通过连接对象获取输出流
            outputStream.write(param.getBytes());//通过输出流对象将参数传输出去,它是通过字节数组写出去的
            System.out.println("respCode:"+conn.getResponseCode());
            if (conn.getResponseCode() == 200){
                inputStream = conn.getInputStream();
                ByteArrayOutputStream baos=new ByteArrayOutputStream();
                byte[] buf = new byte[1024];
                int len = 0;
                while((len=inputStream.read(buf))!=-1){
                    baos.write(buf, 0, len);
                }
                baos.flush();
                result = baos.toString();
            }<br>       //如果响应码是307则重新发起请求
            if(307 == conn.getResponseCode()) {
                String redirectUrl = conn.getHeaderField("Location");
                if(redirectUrl != null && !redirectUrl.isEmpty()) {
                    urlStr = redirectUrl;
                    return doPostReq(urlStr,param);
                }
            }
 
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (null != bufferedReader){
                    bufferedReader.close();
                }
                if (null != inputStream){
                    inputStream.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
 
        return result;
    }
 
private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
 
 
private static void trustAllHosts() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
 
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }
 
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        } };
        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
posted @   yizw  阅读(2732)  评论(1编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
点击右上角即可分享
微信分享提示