httpcomponents https请求实例

@Test
    public void test4() throws Exception {
        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts
                .custom()
                .loadTrustMaterial(new File("D:\\tomcat.keystore"),
                        "1qaz2wsx".toCharArray(), new TrustSelfSignedStrategy())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());

        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();

        HttpPost httpPost = null;
        CloseableHttpResponse response = null;
        try {

            httpPost = new HttpPost(
                    "https://58.215.50.52:38443/openapi/openapi");

            String params = getParam();

            HttpEntity entity_request = new StringEntity(params, "UTF-8");
            httpPost.setEntity(entity_request);

            System.out.println("Executing request " + httpPost.getRequestLine());

            response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            print(entity.getContent());
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());

            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            response.close();
            httpclient.close();
        }
    }

    private void print(InputStream is) throws IOException{
        int len = 0;
        byte b[] = new byte[1024];
        while((len = is.read(b)) != -1){
            System.out.println(new String(b,Charset.forName("UTF-8")));
        }
    }

    private String getParam(){
        JsonObject jObj = new JsonObject();
        jObj.addProperty("cmd", "register");

        JsonObject jsonElement1 = new JsonObject();
        jsonElement1.addProperty("devKey", "rundong123");
        jObj.add("auth", jsonElement1);

        JsonObject jsonElement2 = new JsonObject();
        jsonElement2.addProperty("userName", "rund");
        jsonElement2.addProperty("password", "000000");
        jsonElement2.addProperty("email", "rd@163.com");
        jsonElement2.addProperty("mobile", "13012345678");
        jObj.add("params", jsonElement2);

        return jObj.toString();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值