IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> Java使用实现无验证书的HTTPS请求 -> 正文阅读

[网络协议]Java使用实现无验证书的HTTPS请求

文章目录

package tv.huan.common.utils.http;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;


public class HttpsUtils {
    private static final Logger log = LoggerFactory.getLogger(HttpsUtils.class);


    /**
     * 融合平台post调用示例
     */
    public static String rhptGet(String url) {
        HttpGet httpGet = new HttpGet(url);
        SSLClient httpClient = null;
        httpGet.addHeader("User-Agent", "Mozilla/5.0(Windows NT 6.1;Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
        httpGet.addHeader("Content-type", "application/x-www-form-urlencoded");
        httpGet.addHeader("other", "xxxxx");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("paramA", "xxxxxxx");
        jsonObject.put("paramB", "123");
        List<NameValuePair> list = new ArrayList<>();
        list.add(new BasicNameValuePair("jsonData", jsonObject.toString()));
        String respMsg = "";
        try {
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, HTTP.UTF_8);
            httpClient = new HttpsUtils().new SSLClient(); // 与DefaultHttpClient httpClient = new DefaultHttpClient(); enableSSL(httpClient); 等价
            // DefaultHttpClient httpClient = new DefaultHttpClient();
            // enableSSL(httpClient);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity httpEntity = response.getEntity();
            respMsg = EntityUtils.toString(httpEntity, "utf-8");

            log.info("发送HTTPS的get请求获取到的响应为" + respMsg);
        } catch (Exception e) {
            log.error("发送HTTPS的get请求异常", e);
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
        }
//        post.setEntity(urlEncodedFormEntity);

        return respMsg;
    }

    /**
     * 融合平台post调用示例
     */
    public static String rhptPost(String url, String params) {
        HttpPost post = new HttpPost(url);
        SSLClient httpClient = null;
        post.addHeader("User-Agent", "Mozilla/5.0(Windows NT 6.1;Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
        post.addHeader("Content-type", "application/x-www-form-urlencoded");
        post.addHeader("other", "xxxxx");

//        JSONObject jsonObject = new JSONObject();
//
//        List<NameValuePair> list = new ArrayList<>();
//        list.add(new BasicNameValuePair("jsonData", jsonObject.toString()));
        String respMsg = "";
        try {
            post.setEntity(new StringEntity(params, HTTP.UTF_8));
//            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
            httpClient = new HttpsUtils().new SSLClient(); // 与DefaultHttpClient httpClient = new DefaultHttpClient(); enableSSL(httpClient); 等价
            // DefaultHttpClient httpClient = new DefaultHttpClient();
            // enableSSL(httpClient);
            CloseableHttpResponse response = httpClient.execute(post);
            HttpEntity httpEntity = response.getEntity();
            respMsg = EntityUtils.toString(httpEntity, "utf-8");

            log.info("发送HTTPS的post请求获取到的响应为" + respMsg);
        } catch (Exception e) {
            log.error("发送HTTPS的post请求异常", e);
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
        }
//        post.setEntity(urlEncodedFormEntity);

        return respMsg;
    }


    /**
     * 访问https的网站
     *
     * @param httpclient
     */
    public static void enableSSL(DefaultHttpClient httpclient) {
        TrustManager[] truseAllManager = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[]{};
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        }};
        //调用ssl
        try {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, truseAllManager, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme https = new Scheme("https", sf, 4433);
            httpclient.getConnectionManager().getSchemeRegistry().register(https);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //用于进行Https请求的HttpClient
    class SSLClient extends DefaultHttpClient {
        public SSLClient() throws Exception {
            super();
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new 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 null;
                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = this.getConnectionManager();
            SchemeRegistry sr = ccm.getSchemeRegistry();
            sr.register(new Scheme("https", 443, ssf));
        }
    }

}
  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-11-29 16:38:29  更:2021-11-29 16:39:51 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/26 9:33:27-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码