HttpClient通信

    /**
     * 默认请求超时时间
     */
    private static final int TIMEOUT = 10000;
    /**
     * 默认连接超时时间
     */
    private static final int SO_TIMEOUT = 10000;
    /**
     * 默认编码
     */
    private static final String CHARSET = "UTF-8";


    /**
     * Http 的post 方式
     * @param params
     * @param charset
     * @return
     * @throws Exception
     */
    public static String postMethod(String url, Map<String, String> params, String charset) throws Exception {
        if (StringUtils.isEmpty(url)) {
            logger.warn("the request url is empty!");
            throw new RuntimeException("post reuqest url is emplty!");
        }
        RequestConfig config = RequestConfig.custom().setConnectTimeout(TIMEOUT).setSocketTimeout(SO_TIMEOUT).build();
        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
        HttpPost httpPost = null;
        String result = null;
        CloseableHttpResponse response = null;
        try {
            httpPost = new HttpPost(url);
            httpPost.addHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));

            List<NameValuePair> pairs = null;
            if (params != null && !params.isEmpty()) {
                pairs = new ArrayList<NameValuePair>(params.size());
                for (String key : params.keySet()) {
                    pairs.add(new BasicNameValuePair(key, params.get(key).toString()));
                }
            }

            if (pairs != null && pairs.size() > 0) {
                httpPost.setEntity(new UrlEncodedFormEntity(pairs, charset));
            }
            response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                    logger.debug("post request to {} and params is {} ,server's response \r\n{}", url, params, result);
                }
            }
        } catch (Exception e) {
            logger.error("Get request error", e);
            throw e;
        } finally {
            response.close();
            httpClient.close();
        }
        return result;
    }
    /**
     * Http 的get 方式
     * @param params
     * @param charset
     * @return
     * @throws Exception
     */
    public static String getMethod(String url, Map<String, String> params, String charset) throws Exception {
        if (StringUtils.isEmpty(url)) {
            logger.warn("the request url is empty!");
            throw new RuntimeException("get reuqest url is emplty!");
        }
        RequestConfig config = RequestConfig.custom().setConnectTimeout(TIMEOUT).setSocketTimeout(SO_TIMEOUT).build();
        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
        CloseableHttpResponse response = null;
        try {
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
                for (String key : params.keySet()) {
                    pairs.add(new BasicNameValuePair(key, params.get(key).toString()));
                }
                url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
            }
            HttpGet httpGet = new HttpGet(url);
            response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
                logger.debug("get request to {} and params is {} ,server's response \r\n{}", url, params, result);
            }
            EntityUtils.consume(entity);
            response.close();
            return result;
        } catch (Exception e) {
            logger.error("Get request error", e);
            throw e;
        } finally {
            response.close();
            httpClient.close();
        }
    }
    /**
     * Http 的post 方式 JSON传参
     */
    public static String postJsonMethod(String url, String params) throws Exception {
         BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(
                                RegistryBuilder.<ConnectionSocketFactory>create()
                                        .register("http",
                                                PlainConnectionSocketFactory.getSocketFactory())
                                        .register("https",
                                                SSLConnectionSocketFactory.getSocketFactory())
                                        .build(),
                                null, null, null);


            HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connManager).build();

            HttpPost httpPost = new HttpPost(url);

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT).setSocketTimeout(SO_TIMEOUT).build();
            httpPost.setConfig(requestConfig);

            StringEntity postEntity = new StringEntity(params, CHARSET);
            httpPost.addHeader("Content-Type", "application/json");

            httpPost.setEntity(postEntity);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            return EntityUtils.toString(httpEntity, "UTF-8");
    }
    /**
     * https 免验密get通信
     */
    public static String getMethod(String url, Map<String, String> params, String charset)
            throws Exception {
        if (StringUtils.isEmpty(url)) {
            LOGGER.warn("the request url is empty!");
            return "";
        }
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpClient httpClient = (CloseableHttpClient) wrapClient(client);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout((int) SO_TIMEOUT)
                .setConnectTimeout((int) TIMEOUT).build();// 设置请求和传输超时时
        CloseableHttpResponse response = null;
        try {
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
                for (String key : params.keySet()) {
                    pairs.add(new BasicNameValuePair(key, params.get(key).toString()));
                }
                url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
            }
            LOGGER.info("getMethod url is {}", url);
            HttpGet httpGet = new HttpGet(url);
            httpGet.setConfig(requestConfig);
            response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
                LOGGER.debug("get request to {} and params is {} ,server's response \r\n{}", url,
                        params, result);
            }
            EntityUtils.consume(entity);
            response.close();
            return result;
        } catch (Exception e) {
            LOGGER.error("Get request error", e);
            throw e;
        } finally {
            response.close();
            httpClient.close();
        }
    }

    /**
     * 避免HttpClient的”SSLPeerUnverifiedException: peer not authenticated”异常 不用导入SSL证书
     * 
     * @param base
     * @return
     */
    public static HttpClient wrapClient(HttpClient base) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                        throws CertificateException {}

                public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                        throws CertificateException {}
            };
            ctx.init(null, new TrustManager[] {tm}, null);
            SSLConnectionSocketFactory ssf =
                    new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
            CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(ssf).build();
            return httpclient;
        } catch (Exception ex) {
            ex.printStackTrace();
            return HttpClients.createDefault();
        }
    }

猜你喜欢

转载自blog.csdn.net/u012418845/article/details/78953506