import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;

import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 引用是很简单,但是,可能提示javax.net.ssl,sslHandshakeexcepiton:received fatal alert :handshake_failure。
 * 这是有两个jdk中有两个安全插件没有更新,第一步先将对应的安全插件 更新到jdk\jre\lib\security下面。
 *安全插件下载地址:https://www.oracle.com/java/technologies/javase-jce8-downloads.html
 */

public class Https_common {
    private static final int SOCKET_TIME_OUT = 60000;    // 设置读取超时
    private static final int CONNECT_TIME_OUT = 60000;    // 设置连接超时
    
    /**
     * 设置请求的参数值
     * @return
     */
    private static RequestConfig getRequestConfig() {
        return RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();
    }

    /**
     * 设置参数列表
     * @param param
     * @return
     */
    private static List<NameValuePair> createParam(Map<String, Object> param) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if(param != null) {
            for(String k : param.keySet()) {
                nvps.add(new BasicNameValuePair(k, param.get(k).toString()));
            }
        }
        return nvps;
    }

    public static CloseableHttpClient createSSLInsecureClient() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // 默认信任所有证书
                public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    return true;
                }
            }).build();
            // AllowAllHostnameVerifier: 这种方式不对主机名进行验证,验证功能被关闭,是个空操作(域名验证)
            SSLConnectionSocketFactory sslcsf = new SSLConnectionSocketFactory(sslContext,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            return HttpClients.custom().setSSLSocketFactory(sslcsf).build();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //如果创建失败,就创建一个默认的Http的连接
        return HttpClients.createDefault();
    }
    /**
     * 无需本地证书keyStore的SSL https带参数请求
     * post K - V 格式的数据
     * @return
     */
    public static String postSSLParams(String url, String param) {
        System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,SSLv3");
        //创建一个信任的连接
        CloseableHttpClient httpClient = createSSLInsecureClient();
        //发送请求的实体类
        HttpPost httpPost = new HttpPost(url);
        //接收返回值
        StringBuilder sb = new StringBuilder();
        BufferedReader br = null;
        try {
//            // 设置客户端请求的头参数getParams已经过时,现在用requestConfig对象替换
//            httpPost.setConfig(getRequestConfig());
//
//            //设置请求的头信息
//            Set<String> keys = headers.keySet();
//            for (String key : keys) {
//                httpPost.setHeader(key, headers.get(key).toString());
//            }

            //这个是设置请求的类型,这个可能需要重点注意下,需要看对方接收的是什么
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            //添加参数, 设置编码格式
            // httpPost.setEntity(new UrlEncodedFormEntity( createParam(params) , Charset.forName("utf-8")));
            httpPost.setEntity(new StringEntity(param , Charset.forName("utf-8")));
            //发送请求
            HttpResponse response = httpClient.execute(httpPost);

            //接收返回值
            HttpEntity httpEntity = response.getEntity();

            //返回值处理
            br = new BufferedReader(new InputStreamReader(httpEntity.getContent(),"utf-8"));
            String s = null;
            while((s=br.readLine())!=null){
                sb.append(s);
            }

        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("指定的编码集不对,您目前指定的编码集是:" + "utf-8");
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException("读取流文件异常",e);
        }catch (Exception e) {
            throw new RuntimeException("通讯未知系统异常",e);
        }finally{
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
    public static void main(String[] args) {

        Https_common hc=  new Https_common();
        String str="<?xml version=\"1.0\" encoding=\"utf-8\"?><SndDt>2020-07-13T14:31:40</SndDt>";
        System.out.println( Https_common.postSSLParams("https://5.8.4.6:8443/A1/net",str));
        //System.out.println( str);
    }
}

 

posted on 2021-05-07 14:53  进_进  阅读(836)  评论(0)    收藏  举报