java 参数和文件同时上传 使用OkHttp3发送https(验证ca证书)请求

1、自建CA证书

参考文章win系统下基于springboot实现https的双向认证。
Linux参考文章Linux下基于springboot实现https的双向认证。

2、代码

2.1 准备工作


keytool -import -alias sslTestClient_01 -file F:\ghj\prooooject\jar\test\client\sslTestClient_01.cer -keystore 'C:\Program Files\Java\jdk1.8.0_261\jre\lib\security\cacerts' -storepass changeit –v


keytool -import -alias sslTestServer_01 -file F:\ghj\prooooject\jar\test\server\sslTestServer_01.cer -keystore 'C:\Program Files\Java\jdk1.8.0_261\jre\lib\security\cacerts' -storepass changeit –v

2.2 GET请求

参考文章自建CA证书,java实现通过OkHttpClient发送https(验证ca证书)请求

2.3 POST请求

核心代码
        // 构造参数。
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name","郑小蕤");
        jsonObject.put("sex","女");
        String paramData = jsonObject.toJSONString();
        // 文件路径
        String filePath = "F:\\ghj\\projects\\test\\2.jpg";
        List pathList = new ArrayList<>();
        pathList.add(filePath);

        MediaType MutilPart_Form_Data = MediaType.parse("multipart/form-data; charset=utf-8");
        MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("data",paramData)
                .addFormDataPart("requestFlag","10011-01")
                .addFormDataPart("type","test");

        for (int i = 0; i < pathList.size(); i++) {
            File file = new File(pathList.get(i));
            requestBodyBuilder.addFormDataPart("files", file.getName(),
                    RequestBody.create(MutilPart_Form_Data, new File(pathList.get(i))));
        }

        RequestBody requestBody = requestBodyBuilder.build();
        Request request = new Request.Builder().url(URL)
                .post(requestBody).build();
        try {
            Response response = client.newCall(request).execute();
            System.err.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }

3、Controller示例

public ResultBody testPostHttps(String requestFlag,String type,String data, @RequestParam("files") MultipartFile[] files) {
    return null;
}

4、测试

返回结果.png

5、完整代码

package com.demo.zxr.common.utils.https;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import javax.net.ssl.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
 * @program: post-https-demo
 * @description:
 * @author: Guanzi
 * @created: 2021/10/21 13:43
 */
public class PostHttpsDemo {


    // test get请求获取版本信息。
    // private final static String URL = "https://180.76.24.107:8888/his/version";
    // test 调用接口获取信息。
    private final static String URL = "https://180.76.24.107:8888/api/sel";
    private final static String CLIENT_CA_PATH = "F:\\ghj\\prooooject\\sslTestServer_01.p12";
    private final static String KEY_STORE_PWD = "zxr20211021..";

    // 证书库
    private final static String KEY_STORE_TYPE = "PKCS12";
    private final static String TRUST_KEY_STORE_TYPE = "JKS";
    private final static String JRE_PATH = "C:\\Program Files\\Java\\jdk1.8.0_261\\jre\\lib\\security\\cacerts";
    private final static String DEFAULT_PWD = "changeit";


    /**
     * 初始化HTTPS实例(需要校验CA)
     */
    private static volatile OkHttpClient client;

    /**
     * ssl socket工厂(需要校验CA)
     */
    private static SSLSocketFactory sslSocketFactory = null;
    private static X509TrustManager trustManager = null;
    private static SSLContext  sslContext = null;


    public static void main(String[] args) throws IOException, UnrecoverableKeyException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        // 初始化
        httpsInit();
        // 发送请求
        thirdSendPostHttps();
    }



    /**
     * 方法 3
     * 此方法需要引入jar包。
     * 
     *   com.squareup.okhttp3
     *   okhttp
     *   3.3.0
     * 
     * @return
     * @throws IOException
     */
    public static String thirdSendPostHttps() throws IOException {
        client = new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.MINUTES)
                .writeTimeout(5, TimeUnit.MINUTES)
                .connectTimeout(5, TimeUnit.MINUTES)
                .sslSocketFactory(sslSocketFactory,trustManager)
                .hostnameVerifier((String hostname, SSLSession session) -> true)
                .build();
        // 构造参数。
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name","郑小蕤");
        jsonObject.put("sex","女");
        String paramData = jsonObject.toJSONString();
        // 文件路径
        String filePath = "F:\\ghj\\projects\\test\\2.jpg";
        List pathList = new ArrayList<>();
        pathList.add(filePath);

        MediaType MutilPart_Form_Data = MediaType.parse("multipart/form-data; charset=utf-8");
        MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("data",paramData)
                .addFormDataPart("requestFlag","10011-01")
                .addFormDataPart("type","test");

        for (int i = 0; i < pathList.size(); i++) {
            File file = new File(pathList.get(i));
            requestBodyBuilder.addFormDataPart("files", file.getName(),
                    RequestBody.create(MutilPart_Form_Data, new File(pathList.get(i))));
        }

        RequestBody requestBody = requestBodyBuilder.build();
        Request request = new Request.Builder().url(URL)
                .post(requestBody).build();
        try {
            Response response = client.newCall(request).execute();
            System.err.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 初始化方法。
     * @throws KeyStoreException
     * @throws IOException
     * @throws CertificateException
     * @throws NoSuchAlgorithmException
     * @throws UnrecoverableKeyException
     * @throws KeyManagementException
     */
    public static void httpsInit() throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
        // 客户端证书类型
        KeyStore clientStore = KeyStore.getInstance(KEY_STORE_TYPE);
        // 加载客户端证书,即p12文件。
        clientStore
                .load(new FileInputStream(CLIENT_CA_PATH),
                        KEY_STORE_PWD.toCharArray());
        // 创建密钥管理工厂实例
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        // 初始化客户端密钥库
        kmf.init(clientStore, KEY_STORE_PWD.toCharArray());
        KeyManager[] kms = kmf.getKeyManagers();
        // 创建信任库管理工厂实例
        TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        // 信任库类型
        KeyStore trustStore = KeyStore.getInstance(TRUST_KEY_STORE_TYPE);
        // 加载信任库,即服务端公钥,jre安装目录。
        trustStore.load(new FileInputStream(JRE_PATH),
                DEFAULT_PWD.toCharArray());
        // 初始化信任库
        tmf.init(trustStore);
        TrustManager[] tms = tmf.getTrustManagers();
        // 建立连接,这里传TLS或SSL其实都可以的
        sslContext = SSLContext.getInstance("TLS");
        // 初始化SSLContext
        sslContext.init(kms, tms, new SecureRandom());
        try {
            sslSocketFactory = sslContext.getSocketFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        trustManager = (X509TrustManager) tms[0];
        return;
    }

}

你可能感兴趣的:(java 参数和文件同时上传 使用OkHttp3发送https(验证ca证书)请求)