HttpClient工具类2

package com.paic.egis.cssp.internet.web.controller.pay.tenpay.util;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.apache.http.HttpEntity;
import com.apache.http.NameValuePair;
import com.apache.http.client.entity.UrlEncodedFormEntity;
import com.apache.http.client.methods.CloseableHttpResponse;
import com.apache.http.client.methods.HttpPost;
import com.apache.http.config.Registry;
import com.apache.http.config.RegistryBuilder;
import com.apache.http.conn.socket.ConnectionSocketFactory;
import com.apache.http.conn.socket.PlainConnectionSocketFactory;
import com.apache.http.conn.ssl.SSLConnectionSocketFactory;
import com.apache.http.impl.client.CloseableHttpClient;
import com.apache.http.impl.client.HttpClients;
import com.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import com.apache.http.message.BasicNameValuePair;
import com.apache.http.util.EntityUtils;
import com.paic.egis.cssp.common.util.LoggerUtil;

/**
*
* @author shaun httpClient发送post请求
*
*/
public class HttpClientNewUtil {
       

        public static Map doPost(String url, Map params,String encoding){
                LoggerUtil.info("通过httpClient发送post请求,入参params="+params+",请求路径url="+url+",编码encoding="+encoding);
                Map resultMap = new HashMap();
                String body="";
                String satatusCode="SUCCESS";
                CloseableHttpResponse response=null;
                try{
                        // 采用绕过验证的方式处理https请求
                        LoggerUtil.info("采用绕过验证的方式处理https请求开始处理。。。。。");
                        CloseableHttpClient httpClient = createIgnoreVerifySSL();
                        LoggerUtil.info("采用绕过验证的方式处理https请求处理完成。。。。。");
                        // 创建post方式请求对象
                        HttpPost httpPost = new HttpPost(url);
                        // 设置参数
                        List nvps = new ArrayList();
                       
                        for (Map.Entry maps : params.entrySet()) {
                                nvps.add(new BasicNameValuePair(maps.getKey(), maps.getValue()));
                        }
                        LoggerUtil.info("通过httpClient发送post请求设置之后的参数:"+nvps);
                        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nvps, encoding);
                        // 设置参数到请求对象中
                        httpPost.setEntity(urlEncodedFormEntity);
                        // 设置header信息
                        // 指定报文头【Content-type】、【User-Agent】
                        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
                        response = httpClient.execute(httpPost);
                        LoggerUtil.info("通过httpClient发送post请求响应response:"+response);
                        // 获取结果实体
                        HttpEntity respEntity = response.getEntity();
                        LoggerUtil.info("通过httpClient发送post请求,获取结果实体:"+respEntity);
                        if (respEntity != null) {
                                //按指定编码转换结果实体为String类型
                                body = EntityUtils.toString(respEntity, encoding);
                                resultMap.put("satatusCode", satatusCode);
                                resultMap.put("body", body);
                                LoggerUtil.info("通过httpClient发送post请求响应实体为:"+body);
                        }else{
                                satatusCode="FAIL";
                                resultMap.put("satatusCode", satatusCode);
                                LoggerUtil.info("通过httpClient发送post请求响应实体为空!");
                        }
                       
                }catch(Exception e){
                        satatusCode="FAIL";
                        resultMap.put("satatusCode", satatusCode);
                        LoggerUtil.info("通过httpClient发送post请求发生异常:"+e);
                }finally{
                        //释放链接
                        try {
                                if(response!=null){
                                        response.close();
                                }
                        } catch (IOException e) {
                                satatusCode="FAIL";
                                resultMap.put("satatusCode", satatusCode);
                                LoggerUtil.info("通过httpClient发送post请求释放链接发生异常:"+e);
                        }
                }
                return resultMap;
        }

        /**
         * @SuppressWarnings("unchecked")
         * @param parms
         * @param url
         * @return
         * @throws BusinessServiceException
         */

        /*
         * public static Map httpCallNbuSendMsg(Map
         * parms, String url) throws BusinessServiceException { Map
         * result = new HashMap(); try { RestTemplate restTemplate =
         * new RestTemplate(); HttpHeaders headers = new HttpHeaders();
         * headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
         *
         * List acceptableMediaTypes = new ArrayList();
         * acceptableMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
         * headers.setAccept(acceptableMediaTypes);
         *
         *
         * HttpEntity> requestEntity = new
         * HttpEntity>(parms, headers);
         * LoggerUtil.info("--httpCallNbuSendMsg----parms---" + parms);
         *
         *
         * restTemplate.getMessageConverters().add(new
         * ExMappingJacksonHttpMessageConverter()); ResponseEntity resp =
         * restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
         *
         * LoggerUtil.info("----httpCallNbuSendMsg----result---" + resp.getBody());
         *
         * String resultStr = resp.getBody();
         *
         * Map map = null;
         *
         * if(StringUtils.isNotEmpty(resultStr)){ map = JSON.parseObject(resultStr,
         * Map.class); }else{ throw new
         * BusinessServiceException("---httpCallNbuSendMsg()--返回信息为空"); }
         *
         * result.put("data", map); } catch (Exception e) {
         * LoggerUtil.info("--httpCallNbuSendMsg()--exception--" + e);
         * result.put("result", "failed"); result.put("message", "调用消息发送失败!"); throw
         * new BusinessServiceException(e.getMessage()); } return result; }
         */
        /**
         * 绕过验证
         *
         * @return
         * @throws NoSuchAlgorithmException
         * @throws KeyManagementException
         */
        public static CloseableHttpClient createIgnoreVerifySSL()
                        throws NoSuchAlgorithmException, KeyManagementException {
                SSLContext sslcontext = SSLContext.getInstance("SSLv3");

                // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
                X509TrustManager trustManager = new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(
                                        java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                                        String paramString) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(
                                        java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                                        String paramString) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                                java.security.cert.X509Certificate[] certificates=new java.security.cert.X509Certificate[]{};
                                return certificates;
                               
                                //return null;
                        }
                };

                sslcontext.init(null, new TrustManager[] { trustManager }, null);
               
               
                // 设置协议http和https对应的处理socket链接工厂的对象
                Registry socketFactoryRegistry = RegistryBuilder
                                . create()
                                .register("http", PlainConnectionSocketFactory.INSTANCE)
                                .register("https", new SSLConnectionSocketFactory(sslcontext))
                                .build();

                PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
                                socketFactoryRegistry);
                HttpClients.custom().setConnectionManager(connManager);
                CloseableHttpClient httpClient = HttpClients.custom()
                                .setConnectionManager(connManager).build();
               
               
                return httpClient;
        }

}

 

你可能感兴趣的:(生命的意义,java)