使用HttpClient访问https协议的接口

自定义HttpClient

使用HttpClients.createDefault()这个默认配置的方法有时候并不能满足需求,无法配置证书和协议,下面代码演示怎样自定义HttpClient.

package com.jiangtengfei.https;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * Created by jiangtengfei on 16/3/2.
 */
public class HttpClientHttpsTest {

    public static void httpsTest() {

        CloseableHttpClient httpClient = null;

        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            }).build();

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();


            if (httpClient != null) {
                HttpGet httpGet = new HttpGet("https://www.baidu.com");

                CloseableHttpResponse response = httpClient.execute(httpGet);

                try {
                    HttpEntity entity = response.getEntity();
                    System.out.println("--------------------------------------");
                    if (entity != null) {
                        System.out.println("Response content length: " + entity.getContentLength());
                        System.out.println(EntityUtils.toString(entity));
                        EntityUtils.consume(entity);
                    }
                } finally {
                    response.close();
                }
            }

        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        HttpClientHttpsTest.httpsTest();
    }
}

有些情况下可能会报这样的错:

javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name

这是可以试试在方法里加上:

System.setProperty ("jsse.enableSNIExtension", "false");

如果需要使用HttpClient获取cookie信息,则在构建HttpClient实例的时候需要加上相关配置:

CookieStore cookieStore = new BasicCookieStor();

httpClient = HttpClients.custom().setSSLSocketFactory(salsa).setDefaultCookieStore(cookieStore).build();

等执行了httpClient.execute(httpGet);后,就可以获取到cookie了:

List cookies = cookieStore.getCookies();

禁止HttpClient follow redirect

要禁止HttpClient重定向,可以传入自定义的DefaultRedirectStrategy重定向策略

HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new DefaultRedirectStrategy() {
     @Override
     protected boolean isRedirectable(String method) {
          return false
     }
}).build()

仅作演示用,不要在意代码风格这些细节

你可能感兴趣的:(使用HttpClient访问https协议的接口)