Https 带证书post请求方法 亲测可用

 

测试代码 Https带证书请求方法敬上,根据业务可能会适当更改传参方式或请求方式

 

@GetMapping(value = "loginSubmit")
    public ApiResult loginSubmit(){
        try {
            long timeStamp = System.currentTimeMillis();
            JSONObject data = new JSONObject();
            String miwen = RSASecureUtil.encrypt("{\"mobile\": \"18954119383\",\"oauthid\": \"18954119383\",\"idno\": \"370125199512297023\",\"name\": \"张三\",\"timeStamp\":"+timeStamp+",\"regdate\":1563743945616}", AppConfig.REG_PUBLICKEY);
            data.put("reqData",miwen);

            System.out.println("data ZString:==="+ data.toString());
            String result = HttpsSSL.postMap1(AppConfig.USER_REG_URL,data.toJSONString());
            JSONObject jsonObject = JSON.parseObject(result);
            return new ApiResult().success(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * @Date 2019/6/20 16:48
     **/
    @GetMapping(value = "loginSubmit1")
    public String loginSubmit1(){
        try {
//            Map<String, String> data = new HashMap<>();
            JSONObject data = new JSONObject();
            long timeStamp = System.currentTimeMillis();
            String miwen = RSASecureUtil.encrypt("{\"mobile\":             \"18954119383\",\"oauthid\": \"18954119383\",\"idno\": \"370125199512297023\",\"name\": \"张三\",\"timeStamp\":"+timeStamp+",\"regdate\":1563743945616}",
 AppConfig.REG_PUBLICKEY);
//            String miwen = RSASecureUtil.encrypt("{\"uuid\": \"370125199511297023\",\"timeStamp\":\""+timeStamp+"\"}", AppConfig.REG_PUBLICKEY);
            data.put("reqData",miwen);

            String ss = data.toJSONString();
            System.out.println("ss:"+ ss);
            //加密请求头
//            Map<String,String> httpHeaders = new HashMap<>();
//            httpHeaders.put("Content-Type","application/json");
            System.out.println("请求开始:============" );
            String result = HttpsSSL.sendPostAndReturn(ss, AppConfig.USER_REG_URL);
            System.out.println("请求结果:" +result);
            return result;
        } catch (Exception e) {
            System.out.println("请求异常" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
 public static String postMap1(String url, String params) throws Exception {
        logger.info("省厅的url=========" + url);
        logger.info("省厅的请求体=========" + JSONObject.toJSONString(params));
        String result = null;
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        InputStream instream = new FileInputStream(new File(AppConfig.PFX_PATH));
        logger.info("证书:" + instream);
        try {
            logger.info("====================2====================");
            keyStore.load(instream, AppConfig.PFX_PWD.toCharArray());
        } finally {
            instream.close();
        }
        logger.info("====================3====================");
        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, AppConfig.PFX_PWD.toCharArray()).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext
                , new String[]{"TLSv1"}    // supportedProtocols ,这里可以按需要设置
                , null    // supportedCipherSuites
                , SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        logger.info("====================4====================");
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        HttpPost post = new HttpPost(url);

        logger.info("====================6====================");
        CloseableHttpResponse response = null;
        try {
            post.addHeader("Content-Type","application/json");
//            if (content.size() > 0) {
//                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(content, "UTF-8");
//                post.setEntity(entity);
//            }
            StringEntity requestEntity = new StringEntity(params,"utf-8");
            post.setEntity(requestEntity);
            //发送请求并接收返回数据
            response = httpClient.execute(post);
            logger.info("返回果为:+++++++++" + JSONObject.toJSONString(response));
            System.out.println(response);


            try {
                HttpEntity  entity = response.getEntity();
                result  = EntityUtils.toString(entity,"utf-8");
                EntityUtils.consume(entity);
                logger.error("returnData=:{}",result);
            } catch (Exception e) {
                logger.error("catch");
            }finally{
                response.close();
            }
            logger.info("请求结果为:+++++++++" + result);
            System.out.println(result);
            return result;
        } catch (UnsupportedEncodingException e) {
            logger.info("请求异常222");
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            logger.info("===================7===================");
            e.printStackTrace();
        } catch (IOException e) {
            logger.info("====================8====================");
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                logger.info("====================9====================");
                e.printStackTrace();
            }

        }
        return null;
    }

    /**
     * HTTPClient ssl认证 发送post请求
     * @param params
     * @param url
     * @return
     */
    public static String sendPostAndReturn(String params, String url) {

        String returnData = "";
        try {
            KeyStore trustStore = KeyStore.getInstance("PKCS12");
            //main方法测试时把这里打开
//            InputStream intream = ClassLoader.getSystemResourceAsStream("client.p12");
            //正式环境部署时打开下面
              InputStream intream = new FileInputStream(new File(AppConfig.PFX_PATH));
            try {

                trustStore.load(intream, AppConfig.PFX_PWD.toCharArray());

            } catch (Exception e) {

            }finally{
                intream.close();
            }
            SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(trustStore, AppConfig.PFX_PWD.toCharArray()).build();
//            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).loadKeyMaterial(trustStore, AppConfig.PFX_PWD.toCharArray()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext
                    ,new String[]{"TLSv1","TLSv1.1","TLSv1.2"}
                    ,null
                    ,SSLConnectionSocketFactory.getDefaultHostnameVerifier());
            CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
            HttpPost httppost = new HttpPost(url);
            httppost.addHeader("Content-type", "application/json; charset=utf-8");
//            httppost.addHeader("Connection", "Close");
            StringEntity requestEntity = new StringEntity(params,"utf-8");
            httppost.setEntity(requestEntity);
            CloseableHttpResponse response = httpClient.execute(httppost);
            logger.error("response=:{}",response);
            try {
                HttpEntity  entity = response.getEntity();
                returnData  = EntityUtils.toString(entity,"utf-8");
                EntityUtils.consume(entity);
                logger.error("returnData=:{}",returnData);
            } catch (Exception e) {
                 logger.error("catch");
            }finally{
                response.close();
            }
        } catch (Exception e) {
            logger.error("catch");
        }

        return returnData;
    }

 

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值