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 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> 后端发送Http请求、忽略SSL检查 -> 正文阅读

[网络协议]后端发送Http请求、忽略SSL检查

后端发送Http请求、忽略SSL检查、OKHttp 跳过SSL检查

1.OKhttp依赖


<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.10.0</version>
</dependency>

2.忽略SSL检查的工具类

package com.maam.personnel.utils;

import javax.net.ssl.*;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Arrays;
/**
 * @Author : lizheng
 * @Date: 2022/3/14 12:49
 * @Version: 1.0
 * @Description:
 */

public class SSLSocketClient {
    /**
     * 获取这个SSLSocketFactory
     * */
    public static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取TrustManager
     * */
    private static TrustManager[] getTrustManager() {
        return new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

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

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
    }

    /**
     * 获取HostnameVerifier
     * */
    public static HostnameVerifier getHostnameVerifier() {
        return (s, sslSession) -> true;
    }

    public static X509TrustManager getX509TrustManager() {
        X509TrustManager trustManager = null;
        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
            }
            trustManager = (X509TrustManager) trustManagers[0];
        } catch (Exception e) {
            e.printStackTrace();
        }

        return trustManager;
    }

}

3. 发送请求


/**
 * OkHttp请求工具类
 */
@Slf4j
public class HttpUtil {

    private final static String APPLICATION_ID = "1498989898989";
    private final static String APPLICATION_NAME = "人员管理 ";
    private final static String UPLOAD_URL = "https://maam-test-maam-caffile-caffile.entry.wanweibiyi.com/caf/file/v1/upload";
    private final static String DOWN_URL = "https://maam-test-maam-caffile-caffile.entry.wanweibiyi.com/caf/file/v1/";

    /**
     * http请求,将图片上传到文件服务器,返回文件id
     * @param base64
     * @return
     */
    public static String fileUploadHttp(String base64){
        FileDTO fileDTO = new FileDTO();
        fileDTO.setApplicationId(APPLICATION_ID);
        fileDTO.setApplicationName(APPLICATION_NAME);
        fileDTO.setBase64(base64);
        String jsonString = JSON.toJSONString(fileDTO);
        Response response = null;
        String responseBody = "";
        String fileId = "";
        try {
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonString);
            Request request = new Request.Builder()
                    .url(UPLOAD_URL)
                    .post(requestBody)
                    .build();
            OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                    .readTimeout(60, TimeUnit.SECONDS)
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), SSLSocketClient.getX509TrustManager())
                    .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                    .build();
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (status == 200 && response.body() != null) {
                responseBody = response.body().string();
                JsonDTO jsonDTO = JSON.parseObject(responseBody, JsonDTO.class);
                fileId= jsonDTO.getData().getId();
            }else {
                responseBody = "error:"+ JSONObject.toJSONString(response);
            }
        } catch (Exception e) {
            log.error("文件服务器接口调用异常:调用地址url={},error = {}",UPLOAD_URL, e.getMessage());
            throw new BusinessException("文件服务器调用异常");
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return fileId;
    }

    /**
     * Http请求,文件服务器,通过文件id,查询文件地址
     * @param fileId
     * @return
     */
    public static String fileDownLoadHttp(String fileId){
        String url = DOWN_URL + fileId;
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
//        OkHttpClient okHttpClient = new OkHttpClient();
        Response response = null;
        String responseBody = null;
        String imgUrl = "";
        try {
            OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                    .readTimeout(60, TimeUnit.SECONDS)
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), SSLSocketClient.getX509TrustManager())
                    .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                    .build();
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (status == 200 && response.body() !=null){
                responseBody = response.body().string();
                JsonUrlDTO jsonUrlDTO = JSON.parseObject(responseBody, JsonUrlDTO.class);
                imgUrl = jsonUrlDTO.getData();
            }else {
                responseBody = "error:"+ JSONObject.toJSONString(response);
            }
        } catch (Exception e) {
            log.error("文件服务器接口调用异常:调用地址url={},error = {}",UPLOAD_URL, e.getMessage());
            throw new BusinessException("文件服务器调用异常");
        }
        finally {
            if (response != null) {
                response.close();
            }
        }
        return imgUrl;
    }

    /**
     * 删除文件服务器文件,http请求
     * @param fileId
     * @return
     */
    public static Boolean deleteFileHttp(String fileId){
        String url = DOWN_URL + fileId;
        Request request = new Request.Builder()
                .url(url)
                .delete()
                .build();
        Response response = null;
        String responseBody = null;
        String imgUrl = "";
        try {
            OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                    .readTimeout(60, TimeUnit.SECONDS)
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), SSLSocketClient.getX509TrustManager())
                    .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                    .build();
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (status == 200 && response.body() !=null){
                return true;
            }else {
                responseBody = "error:"+ JSONObject.toJSONString(response);
                return false;
            }
        } catch (Exception e) {
            log.error("文件服务器接口调用异常:调用地址url={},error = {}",UPLOAD_URL, e.getMessage());
            throw new BusinessException("文件服务器调用异常");
        }
        finally {
            if (response != null) {
                response.close();
            }
        }
    }
}

4. 测试

public static void main(String[] args) {
    Boolean aBoolean = HttpUtil.deleteFileHttp("b8e44ec45efd44c3bfe96e0606a66bcc");
    System.out.println(aBoolean);

    String s = HttpUtil.fileDownLoadHttp("332b8655b27d4d509a0dd196754c6684");
    System.out.println(s);

}
  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2022-03-15 23:04:40  更:2022-03-15 23:04:43 
 
开发: 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 6:25:07-

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