java 用httpClient 根据ca.crt、client.crt和client.key文件实现与服务端https通讯





    public static SSLConnectionSocketFactory getSSLSocktetBidirectional() throws Exception {
        SSLConnectionSocketFactory sslsf = null;

        try{
// CA certificate is used to authenticate server
            String linuxLocalIp = IpDataUtils.getSelfPublicIp();
            //正式环境代码,配置正常逻辑代码
          
            CertificateFactory cAf = CertificateFactory.getInstance("X.509");
            FileInputStream caIn = new FileInputStream(CA_PATH);
            X509Certificate ca = (X509Certificate) cAf.generateCertificate(caIn);
            KeyStore caKs = KeyStore.getInstance("JKS");
            caKs.load(null, null);
            //caKs.setCertificateEntry("ca-certificate", ca);
            caKs.setCertificateEntry("verify", ca);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
            tmf.init(caKs);
// client key and certificates are sent to server so it can authenticate us
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            FileInputStream crtIn = new FileInputStream(CRT_PATH);
            X509Certificate caCert = (X509Certificate) cf.generateCertificate(crtIn);
            crtIn.close();

            KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(null, null);
            ks.setCertificateEntry("certificate", caCert);
            ks.setKeyEntry("private-key", getPrivateKey(KEY_PATH), PASSWORD.toCharArray(), new java.security.cert.Certificate[] { caCert });
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
            kmf.init(ks, PASSWORD.toCharArray());
// finally, create SSL socket factory
            SSLContext context = SSLContext.getInstance("TLSv1.2");
            context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());

            sslsf = new SSLConnectionSocketFactory(context,null, null,NoopHostnameVerifier.INSTANCE);
        }catch (Exception e){
            System.out.println("证书加载失败");
            e.printStackTrace();
        }

        return sslsf;
    }




  private static PrivateKey getPrivateKey(String path) throws Exception {
//byte[] buffer = Base64.getDecoder().decode(getPem(path));
// Base64 base64 = new Base64();
       
        BASE64Decoder base64Decoder = new BASE64Decoder();
        byte[] buffer = base64Decoder.decodeBuffer(getPem(path));
        BASE64Decoder decoder = new BASE64Decoder();
        //byte[] buffer = decoder.decodeBuffer(getPem(path));
        //PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(getPem(path)));

      /*  PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
        KeyFactory keyFactory = KeyFactory.getInstance("EC");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;*/

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(keySpec);
    }





private static String getPem(String path) throws Exception {
        FileInputStream fin = new FileInputStream(path);
        BufferedReader br = new BufferedReader(new InputStreamReader(fin));
        String readLine = null;
        StringBuilder sb = new StringBuilder();
        while ((readLine = br.readLine()) != null) {
            if (readLine.charAt(0) == '-') {
                continue;
            } else {
                sb.append(readLine);
                sb.append('\r');
            }
        }
        fin.close();
        return sb.toString();
    }

以上没什么就直接帖代码就行

接下来

  
   public static  String CA_PATH = "C:/Users/lsy/Desktop/certs/ca.crt";
    public static  String CRT_PATH = "C:/Users/lsy/Desktop/certs/client.crt";
    public static  String KEY_PATH = "C:/Users/lsy/Desktop/certs/client.key";
    public static  String PASSWORD = "lisenyuan";

 public static String httpPost( List<shengxinFileDataVm> list) throws IOException {
        CloseableHttpClient httpClient = null;
        List<ShengxinDataAdd> listData=new ArrayList();
        JSONObject jsonObject = new JSONObject();
      /* Map map=new HashMap<>();*/
        ShengxinDataAdd shengxindataadd=new ShengxinDataAdd();
        StringBuffer sb1=new StringBuffer();
        StringBuffer sb2=new StringBuffer();
        String linuxLocalIp = IpDataUtils.getSelfPublicIp();
        String igIp=null;


        for (int i = 0; i < list.size(); i++) {

            ShengxinFileData shengxinFileData1 = list.get(i);
            sb1.append(shengxinFileData1.getSequencingNumber());
            sb1.append(",");
            sb2.append(shengxinFileData1.getSpecimenName());
            sb2.append(",");

        }
        shengxindataadd.setSequencingNumber(sb1.substring(0,sb1.length()-1));
        shengxindataadd.setSpecimenName(sb2.substring(0,sb2.length()-1));
        shengxindataadd.setTaskId(list.get(0).getTaskId().toString());
        shengxindataadd.setProjectNumber(list.get(0).getProjectNumber());
        shengxindataadd.setPanelNumber(list.get(0).getPanel());
        shengxindataadd.setFileType(list.get(0).getFileType());
        shengxindataadd.setContractNumber(list.get(0).getContractNumber());
        shengxindataadd.setCallback(igIp);
        String stringJSON = JSON.toJSONString(shengxindataadd);
        String result = null;
       // System.out.println("请求数据:"+jsonObject.toJSONString());
        System.out.println("请求数据:"+stringJSON);

        try{
            SSLConnectionSocketFactory sslsf = getSSLSocktetBidirectional();
//设置认证信息到httpclient
            httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        }catch (Exception e){
            System.out.println("证书读取失败");
            e.printStackTrace();
            return "证书读取失败";

        }
// 根据默认超时限制初始化requestConfig
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(25000).setConnectTimeout(25000).build();
//post通讯初始化
        HttpPost httpPost = new HttpPost("https:");
// 设置报文头 得指明使用UTF-8编码,否则到API服务器XML的中文不能被成功识别
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
/*        httpPost.addHeader("igIp", igIp);*/
//添加请求报文体
        StringEntity reqentity = new StringEntity(stringJSON, "UTF-8");
        httpPost.setEntity(reqentity);
// 设置请求器的配置
        httpPost.setConfig(requestConfig);
        try {
            CloseableHttpResponse response = null;
            InputStream reqin = null;
            try {
//打印请求报文体
                reqin = httpPost.getEntity().getContent();
                String reqBbody = StreamUtils.copyToString(reqin, StandardCharsets.UTF_8);
                System.out.println("请求数据:"+reqBbody);
//与服务端通讯
                response = httpClient.execute(httpPost);

//打印通讯状态
                System.out.println(JSONObject.toJSONString(response.getStatusLine()));
                JSONObject.toJSONString(response.getStatusLine());

                HttpEntity entity = response.getEntity();
                InputStream in = null;
                try {

                    in = entity.getContent();
                    String rspBbody = StreamUtils.copyToString(in, StandardCharsets.UTF_8);
                    System.out.println("应答为:"+rspBbody);
                    in.close();

                    if(response.getStatusLine().getStatusCode()==200){
                        result="成功";
                    }else{
                        result="失敗";
                    }

// result = EntityUtils.toString(entity, "UTF-8");


                } catch (IOException e) {
                    System.out.println("服务端应答信息读取失败");
                    e.printStackTrace();
                    return "服务端应答信息读取失败";
                }finally {
                    if (in !=null){
                        in.close();
                    }
                }

            } catch (IOException e) {
                System.out.println("与服务端通讯失败");
                e.printStackTrace();
                return "与服务端通讯失败";
            }finally {
                try{
                //释放资源
                    if (httpClient != null){
                        httpClient.close();
                    }
                    if (response != null){
                        response.close();
                    }
                    if (reqin != null){
                        reqin.close();
                    }
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } finally {
            httpPost.abort();
        }
        return result;

    }

重要的来了,有人不知道哪里lisenyuan 这个字符串是怎么来的

keytool -import -alias mycert -keystore cacerts -file C:/Users/lsy/Desktop/certs/ca.crt

执行上面命令设置就行了

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
以下是一个使用org.apache.http.client.HttpClient上传文件Java示例: ```java import java.io.File; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class FileUploader { public static void main(String[] args) { String url = "http://example.com/upload"; String filePath = "/path/to/file.jpg"; HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("file", new File(filePath)); HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); try { httpClient.execute(httpPost); HttpEntity responseEntity = httpResponse.getEntity(); String responseString = EntityUtils.toString(responseEntity, "UTF-8"); System.out.println(responseString); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 在此示例中,我们使用HttpClient创建一个HttpPost请求对象,并使用MultipartEntityBuilder创建一个multipart/form-data实体,以便我们可以将文件作为二进制数据添加到请求中。最后,我们使用execute方法将请求发送到服务器,并从响应中提取响应字符串。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值