/**

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>
<!-- HttpClient-->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.9</version>
</dependency>
<!--<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.6</version>
</dependency>-->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.18</version>
</dependency>





*/

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

public class httpClientUtil {

//采用绕过验证的方式处理https请求
   // SSLContext sslcontext = createIgnoreVerifySSL();
public static CloseableHttpClient getIgnoeSSLClient() throws Exception {
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {

        public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            return true;
        }
    }).build();



    //CloseableHttpClient client = HttpClients.createDefault();*/

    //设置协议http和https对应的处理socket链接工厂的对象

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslContext))
            .build();

    //HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(rrrr);

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);



    //创建httpClient
    CloseableHttpClient client = HttpClients.custom()
                                            .setSSLContext(sslContext).setConnectionManager(connManager).
                                            setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
    return client;
}


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

    CloseableHttpClient httpClient =getIgnoeSSLClient();
    CloseableHttpClient httpClient1 = null;

   // try {

  /*      // 加载自定义的keystore
       // SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new File("D:/java/IdeaProjects/test/src/main/resources/certs/my.keystore"), "123456".toCharArray()).build();

        SSLContext sslContext = createIgnoreVerifySSL();
        // 默认的域名校验类为DefaultHostnameVerifier,比对服务器证书的AlternativeName和CN两个属性。
        // 如果服务器证书这两者不合法而我们又必须让其校验通过,则可以自己实现HostnameVerifier。
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new HostnameVerifier() {
            public boolean verify(String s, SSLSession sslSession) {
                // 我们可以重写域名校验逻辑
                return true;
            }
        });

        // 一个httpClient对象对于https仅会选用一个SSLConnectionSocketFactory
        // 至少在4.5.3和4.5.4中,如果给HttpClient对象设置ConnectionManager,我们必须在PoolingHttpClientConnectionManager的构造方法中传入Registry,
        // 并将https对应的工厂设置为我们自己的SSLConnectionSocketFactory对象,因为在DefaultHttpClientConnectionOperator.connect()中,逻辑是从这里找SSLConnectionSocketFactory的。
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslConnectionSocketFactory)
                .build());
        connectionManager.setMaxTotal(20);
        connectionManager.setDefaultMaxPerRoute(20);

        httpClient1 = HttpClients.custom()
                // 不在connectionManager中注册,仅在这里设置SSLConnectionSocketFactory是无效的,详见build()内部逻辑,在connectionManager不为null时,不会使用里的SSLConnectionSocketFactory
                .setSSLSocketFactory(sslConnectionSocketFactory)
                .setConnectionManager(connectionManager)
                .build();*/

 /*       httpClient = getIgnoeSSLClient();


        HttpGet httpGet = new HttpGet("https://www.12306.cn");
        System.out.println("Executing request " + httpGet.getRequestLine());
        CloseableHttpResponse response = httpClient.execute(httpGet);
        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8"));

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != httpClient) {
                httpClient.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/



    String body = "";

  /*  //采用绕过验证的方式处理https请求
    SSLContext sslcontext = createIgnoreVerifySSL();
    //设置协议http和https对应的处理socket链接工厂的对象
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext))
            .build();
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    HttpClients.custom().setConnectionManager(connManager);

    //创建自定义的httpclient对象
    CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
    //CloseableHttpClient client = HttpClients.createDefault();*/

    try{
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost("https://www.douban.com/service/apikey/apply");//https://api.douban.com/v2/book/1220562


        //指定报文头Content-type、User-Agent
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");

        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");

        //setConnectTimeout:设置连接超时时间,单位毫秒。
        //setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
        //setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。


        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(5000).build();


        httpPost.setConfig( requestConfig);

        //apikey: "0b2bdeda43b5688921839c8ecb20399b"

        Map<String,String> params = new HashMap<String, String>();
        params.put("apikey","0b2bdeda43b5688921839c8ecb20399b");

        StringEntity stringEntity = new StringEntity(JSON.toJSONString(params),"utf-8");
        httpPost.setEntity(stringEntity);


        //执行请求操作,并拿到结果(同步阻塞)
        CloseableHttpResponse response = httpClient.execute(httpPost);

        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, "UTF-8");
        }

        EntityUtils.consume(entity);
        //释放链接
        response.close();
        System.out.println("body:" + body);
    }finally{
        httpClient.close();
    }




}




public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext sc = SSLContext.getInstance("SSLv3");

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

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

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    sc.init(null, new TrustManager[] { trustManager }, null);
    return sc;
}


}


rockyzhang
3 声望0 粉丝

JavaDeveloper at ShangHai