httpcomponents-client-4.3.4 HTTPS地址访问

来源:互联网 发布:焦大seo教程 编辑:程序博客网 时间:2024/05/22 07:56
基于httpcomponents-client-4.3.4进行https地址访问,在网上收集做法如下(未验证其正确性,仅供参考):

1.引用httpcomponents-client-4.3.4中的相关jar包,引用org.json.jar

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

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

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
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.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class HcTest0{

public void test0(String appid, String secret){


try{
            SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {//信任所有
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
            HttpGet get = new HttpGet(url);    
            HttpResponse response = httpclient.execute(get);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                String responseContent = EntityUtils.toString(entity, "UTF-8");
                JSONObject demoJson = new JSONObject(responseContent);
                System.out.print(demoJson.getString("access_token"));
                //EntityUtils.consume(entity);
            }
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

}

}

----------------------------------------------------------------------------

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

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

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.SingleClientConnManager;

public class HcTest1{

public void test1(String appid, String secret){

try{
            X509TrustManager x509mgr = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] xcs, String string) {
                }
                public void checkServerTrusted(X509Certificate[] xcs, String string) {
                }
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[] { x509mgr }, null);
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            CloseableHttpClient httpclient  = HttpClients.custom().setSSLSocketFactory(sslsf).build();

            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
            HttpGet get = new HttpGet(url);    
            HttpResponse response = httpclient.execute(get);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                String responseContent = EntityUtils.toString(entity, "UTF-8");
                JSONObject demoJson = new JSONObject(responseContent);
                System.out.print(demoJson.getString("access_token"));
            }
        }catch(NoSuchAlgorithmException e){
            e.printStackTrace();
        }catch(KeyManagementException e){
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
}

public void test2(String appid, String secret){

try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                //信任所有
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            CloseableHttpClient httpclient  = HttpClients.custom().setSSLSocketFactory(sslsf).build();

            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
            HttpGet get = new HttpGet(url);    
            HttpResponse response = httpclient.execute(get);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                String responseContent = EntityUtils.toString(entity, "UTF-8");
                JSONObject demoJson = new JSONObject(responseContent);
                System.out.print(demoJson.getString("access_token"));
            }
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

}

public void test3(String appid, String secret){
    try {
        HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
        DefaultHttpClient client = new DefaultHttpClient();
        SchemeRegistry registry = new SchemeRegistry();
        SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
        socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
        registry.register(new Scheme("https", socketFactory, 443));
        SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
        DefaultHttpClient httpclient = new DefaultHttpClient(mgr, client.getParams());

        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
            HttpGet get = new HttpGet(url);    
            HttpResponse response = httpclient.execute(get);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                String responseContent = EntityUtils.toString(entity, "UTF-8");
                JSONObject demoJson = new JSONObject(responseContent);
                System.out.print(demoJson.getString("access_token"));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
}

}

参考资料地址: http://www.wuzhuti.cn/201423!528!04!094233.html (缺MySSLSocketFactory实现)

我猜测MySSLSocketFactory可能的实现如下:

import javax.net.ssl.HostnameVerifier;

import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;

public class MySSLSocketFactory {
    private static SSLSocketFactory socketFactory = null;

    @SuppressWarnings("deprecation")
    public static SocketFactory getInstance() {
        if(null == socketFactory){
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            socketFactory = SSLSocketFactory.getSocketFactory();
            socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
        }
        return socketFactory;
    }

}

其它参考资料地址: http://blog.csdn.net/lyq8479/article/details/9841371

                                  http://jingyan.baidu.com/article/e52e3615a2b18f40c60c51d1.html

                                  http://www.cnblogs.com/chenying99/p/3735282.html

                                  http://www.bingobing.net/archives/495

                                  如何访问https的网站?-【httpclient】
                                  http://www.wyjava.com/html/2014/j2ee_jsp_0103/1476.html
                                  HttpClient v4.3 例子: Https, Basic Auth, Get/Post
                                  http://my.oschina.net/sub/blog/169795
                                  Java Code Examples for org.apache.http.conn.scheme.SchemeRegistry
                                  http://www.programcreek.com/java-api-examples/index.php?api=org.apache.http.conn.scheme.SchemeRegistry
                                  HttpsURLConnection和DefaultHttpClient连接HTTPS不用证书
                                  http://blog.csdn.net/actual_/article/details/6968979
0 0
原创粉丝点击