访问https问题

package com.yuantiao.smartcardms.tools;

import com.alibaba.fastjson.JSONObject;
import com.yuantiao.smartcardms.util.MyX509TrustManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;


import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.Map.Entry;

/**
 * 跨域工具类
 *
 * @author CNZZ
 * @time 2019-06-14
 *
 */
public class CrossDomainTool {
    private static Logger log = LoggerFactory.getLogger(CrossDomainTool.class);

    /**
     * post的req.getParameterMap()
     *
     * @param req
     * @return
     */
    public static Map<String, String> getRequestParamMap(HttpServletRequest req) {
        Map<String, String> notifyMap = new HashMap<>();
        Map<String, String[]> parameterMap = req.getParameterMap();
        for (Entry<String, String[]> stringEntry : parameterMap.entrySet()) {
            if (stringEntry.getValue() != null
                    && stringEntry.getValue().length > 0) {
                notifyMap.put(stringEntry.getKey(), stringEntry.getValue()[0]);
            }
        }
        return notifyMap;
    }

//  /**
//   * 响应
//   *
//   * @param response
//   */
//  public static void doResponse(HttpServletResponse response,
//                                  SystemResult systemResult) {
//      log.info("响应参数打印|systemResult={}",
//              JSONObject.toJSONString(systemResult));
//      response.setContentType("application/json");
//      PrintWriter out = null;
//      try {
//          out = response.getWriter();
//          out.write(JSONObject.toJSONString(systemResult));
//      } catch (IOException e) {
//          // TODO Auto-generated catch block
//          e.printStackTrace();
//          log.error("系统响应异常|e={}", e);
//      } finally {
//          out.flush();
//          out.close();
//      }
//  }

    /**
     * 响应
     *
     * @param response
     */
//  public static void doResponse(HttpServletResponse response, String code,
//                                  String msg, Object data) {
//      log.info("响应参数打印|code={},msg={},data={}", code, msg, data);
//      SystemResult systemResult = new SystemResult(code, msg, data);
//      response.setContentType("application/json");
//      PrintWriter out = null;
//      try {
//          out = response.getWriter();
//          out.write(JSONObject.toJSONString(systemResult));
//      } catch (IOException e) {
//          // TODO Auto-generated catch block
//          e.printStackTrace();
//          log.error("系统响应异常|e={}", e);
//      } finally {
//          out.flush();
//          out.close();
//      }
//  }

    /**
     * @description:使用httpClient对象执行 post 请求
     * @param: uri 需要跨域请求的uri , formDataMap 模拟表单需要提交数据 (name - value 形式)
     * @author CNZZ
     * @createDate 2019-05-28
     */
    public static String doPost(String uri, Map<String, Object> formDataMap)
            throws ClientProtocolException, IOException {

        if (StringUtils.isBlank(uri)) {
            return null;
        }

        // 1、创建httpClient 对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 2、 创建post 对象
        HttpPost post = new HttpPost(uri);
        // 3、 创建一个list形式数据,模拟提交表单。
        List<NameValuePair> formDataList = new ArrayList<>();
        // TODO: 这里可以遍历模拟表单传递过来的数据 formDataMap

        Iterator<Entry<String, Object>> iterator = formDataMap.entrySet()
                .iterator();
        while (iterator.hasNext()) {
            Entry<String, Object> next = iterator.next();
            String key = next.getKey();
            String value = next.getValue().toString();
            formDataList.add(new BasicNameValuePair(key, value));
        }

        // formDataList.add(new BasicNameValuePair("ids", "110"));
        // formDataList.add(new BasicNameValuePair("name", "httpClient 请求数据"));
        // 4、 把表单数据包装到entity 对象中 (StringEntity)
        StringEntity formData = new UrlEncodedFormEntity(formDataList, "UTF-8");
        post.setEntity(formData);
        //post.setHeader("Content-type", "application/json;charset=utf-8");
        // 5、 执行post请求
        CloseableHttpResponse response = httpClient.execute(post);

        // 6、 获取响应数据
        HttpEntity entity = response.getEntity();

        StatusLine statusLine = response.getStatusLine();

        // 7、 响应数据转换为字符串
        String data = EntityUtils.toString(entity,"utf-8");
        // 8、 关闭 httpClient对象、关闭 response
        response.close();
        httpClient.close();
        return data;
    }

    private static CloseableHttpClient buildSSLCloseableHttpClient()
            throws Exception {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
                new TrustStrategy() {
                    // 信任所有
                    public boolean isTrusted(X509Certificate[] chain,
                                             String authType) throws CertificateException {
                        return true;
                    }
                }).build();
        // ALLOW_ALL_HOSTNAME_VERIFIER:这个主机名验证器基本上是关闭主机名验证的,实现的是一个空操作,并且不会抛出javax.net.ssl.SSLException异常。
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    }

//  private static CloseableHttpClient getInstance() throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException {
//      // 创建SSLContext对象,并使用我们指定的信任管理器初始化
//      TrustManager[] tm = { new MyX509TrustManager() };
//      SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
//      sslContext.init(null, tm, new java.security.SecureRandom());
//      // 从上述SSLContext对象中得到SSLSocketFactory对象
//      SSLSocketFactory ssf = sslContext.getSocketFactory();
//      return HttpClients.custom().setSSLSocketFactory(ssf).build();
//  }

    public static String doPostSSL(String uri, Map<String, Object> formDataMap)
            throws Exception {

        if (StringUtils.isBlank(uri)) {
            return null;
        }

        // 1、创建httpClient 对象
        CloseableHttpClient httpClient = buildSSLCloseableHttpClient();
        // 2、 创建post 对象
        HttpPost post = new HttpPost(uri);
        // 3、 创建一个list形式数据,模拟提交表单。
        List<NameValuePair> formDataList = new ArrayList<>();
        // TODO: 这里可以遍历模拟表单传递过来的数据 formDataMap

        Iterator<Entry<String, Object>> iterator = formDataMap.entrySet()
                .iterator();
        while (iterator.hasNext()) {
            Entry<String, Object> next = iterator.next();
            String key = next.getKey();
            String value = next.getValue().toString();
            formDataList.add(new BasicNameValuePair(key, value));
        }

        // formDataList.add(new BasicNameValuePair("ids", "110"));
        // formDataList.add(new BasicNameValuePair("name", "httpClient 请求数据"));
        // 4、 把表单数据包装到entity 对象中 (StringEntity)
        StringEntity formData = new UrlEncodedFormEntity(formDataList, "UTF-8");
        post.setEntity(formData);
        //post.setHeader("Content-type", "application/json;charset=utf-8");
        // 5、 执行post请求
        CloseableHttpResponse response = httpClient.execute(post);

        // 6、 获取响应数据
        HttpEntity entity = response.getEntity();

        StatusLine statusLine = response.getStatusLine();

        // 7、 响应数据转换为字符串
        String data = EntityUtils.toString(entity,"utf-8");
        // 8、 关闭 httpClient对象、关闭 response
        response.close();
        httpClient.close();
        return data;
    }
}
12-29 22:46