CloseableHttpAsyncClient

private static HttpClientContext context = HttpClientContext.create();

    /**
     * http async get
     *
     * @param url
     * @param data
     * @return
     */
    public static void doGet(String url, String data) {
        CookieStore cookieStore = new BasicCookieStore();
        final CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();

        httpClient.start();
        HttpGet httpGet = new HttpGet(url);
        //httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
        try {
            httpClient.execute(httpGet, context, new FutureCallback<HttpResponse>() {
                @Override
                public void completed(HttpResponse result) {
                    String body="";
                    //这里使用EntityUtils.toString()方式时会大概率报错,原因:未接受完毕,链接已关
                    try {
                        HttpEntity entity = result.getEntity();
                        if (entity != null) {
                            final InputStream instream = entity.getContent();
                            try {
                                final StringBuilder sb = new StringBuilder();
                                final char[] tmp = new char[1024];
                                final Reader reader = new InputStreamReader(instream,"UTF-8");
                                int l;
                                while ((l = reader.read(tmp)) != -1) {
                                    sb.append(tmp, 0, l);
                                }
                                body = sb.toString();
                                System.out.println(body);
                            } finally {
                                instream.close();
                                EntityUtils.consume(entity);
                            }
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        close(httpClient);
                    }
                }

                @Override
                public void failed(Exception ex) {
                    System.out.println(ex.toString());
                    close(httpClient);
                }

                @Override
                public void cancelled() {

                }
            });
        } catch (Exception e) {
        }

        System.out.println("end-----------------------");
    }

    /**
     * http async post
     *
     * @param url
     * @param values
     * @return
     */
    public static void doPost(String url, List<NameValuePair> values) {
        CookieStore cookieStore = new BasicCookieStore();
        CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();

        HttpPost httpPost = new HttpPost(url);
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Consts.UTF_8);
        httpPost.setEntity(entity);
        try {
            httpClient.execute(httpPost, context, new FutureCallback<HttpResponse>() {
                @Override
                public void completed(HttpResponse result) {
                    System.out.println(result.toString());
                }

                @Override
                public void failed(Exception ex) {
                    System.out.println(ex.toString());
                }

                @Override
                public void cancelled() {

                }
            });
        } catch (Exception e) {
        }
    }

    private static void close(CloseableHttpAsyncClient client) {
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 直接把Response内的Entity内容转换成String
     *
     * @param httpResponse
     * @return
     */
    public static String toString(CloseableHttpResponse httpResponse) {
        // 获取响应消息实体
        String result = null;
        try {
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    public static void main(String[] args) throws Exception {


        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(50000)   //连接超时,连接建立时间,三次握手完成时间
                .setSocketTimeout(50000)  //请求超时,数据传输过程中数据包之间间隔的最大时间
                .setConnectionRequestTimeout(1000)  //使用连接池来管理连接,从连接池获取连接的超时时间
                .build();

        //配置io线程
        IOReactorConfig ioReactorConfig = IOReactorConfig.custom().
                setIoThreadCount(Runtime.getRuntime().availableProcessors())
                .setSoKeepAlive(true)
                .build();
        //设置连接池大小
        ConnectingIOReactor ioReactor = null;
        try {
            ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
        } catch (IOReactorException e) {
            e.printStackTrace();
        }

        PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(ioReactor);
        connManager.setMaxTotal(100);
        connManager.setDefaultMaxPerRoute(100);


        CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
                .setConnectionManager(connManager)
                .setDefaultRequestConfig(requestConfig).build();

        try {

            httpclient.start();
            //String url = "https://webpaywg.bestpay.com.cn/barcode/placeOrder";
            //HttpGet request = new HttpGet("http://www.apache.org/");
            String url = "http://localhost:8080/pay_info";
            HttpPost httpPost = new HttpPost(url);

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

            String date_time = simpleDateFormat.format(new Date());
            System.out.println("date_time = " + date_time);

            String key = "ABCDEF";
            String merchant_id = "987946459879";
            String order_no = "2018082700012";
            String order_req_no = "111113";
            String barcode = "510267678301150238";
            String order_amt = "1";
            String sign = "MERCHANTID=" + merchant_id + "&ORDERNO=" + order_no + "&ORDERREQNO=" + order_req_no + "&ORDERDATE=" + date_time + "&BARCODE=" + barcode + "&ORDERAMT=" + order_amt + "&KEY=" + key;
            String content = "merchantId=" + merchant_id + "&barcode=" + barcode + "&orderNo=" + order_no + "&orderReqNo=" + order_req_no + "&channel=05&busiType=0000001&orderDate=" + date_time + "&orderAmt=" + order_amt + "&productAmt=1&attachAmt=0&storeId=123&mac=" + MD5(sign);
            StringEntity postEntity = new StringEntity(content);
            postEntity.setContentType("application/x-www-form-urlencoded");
            //httpPost.setHeader("content-type","application/json");
            Future<HttpResponse> future = httpclient.execute(httpPost, null);
            httpPost.setEntity(postEntity);
            HttpResponse response = future.get();
            System.out.println("Response: " + response.getStatusLine());
            HttpEntity httpEntity = response.getEntity();
            String result = EntityUtils.toString(httpEntity);
            System.out.println("Response Data:" + result);
            System.out.println("Shutting down");
        } finally {
            httpclient.close();
        }
        System.out.println("Done");
    }

    private static String MD5(String s) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(s.getBytes("utf-8"));
            return toHex(bytes);
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String toHex(byte[] bytes) {

        final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (int i=0; i<bytes.length; i++) {
            ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
        }
        return ret.toString();
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值