springMVC、https、GET调用别人提供的接口!!!

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
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.TrustStrategy;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import sun.net.www.protocol.http.AuthCache;

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

/**
 * Created by zml on 16-11-16.\
 * https的GET方式调用别人的接口,其实也可以用于http协议的,注意看代码的注释
 */
public class HttpsGET {
    //如果给的链接是www.baidu.com这种域名而不是IP,就在cmd黑窗口ping一下域名就可以得到IP地址
    String ip = "xxxx.xxx.xx.xx";
    //如果给的链接没有端口号,则默认写为-1
    int port = -1;
    //接口调用所使用的协议
    String protocol = "https";

    String username = "zhangsan";
    String password = "password";


    public String httpsRequestsGet(String apiUrl){

        String responseBody = "";
        //注册协议并获取链接对象
        CloseableHttpClient httpClient = getHttpClient();

        HttpHost targetHost = new HttpHost(ip,port,protocol);

        //验证主机名端口号和用户名密码
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(targetHost.getHostName(),targetHost.getPort()),
                                           new UsernamePasswordCredentials(username,password));

        org.apache.http.client.AuthCache authScope = new BasicAuthCache();
        BasicScheme basicScheme = new BasicScheme();

        authScope.put(targetHost,basicScheme);

        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credentialsProvider);
        context.setAuthCache(authScope);

        String url = protocol + "://" + ip + ":" + port + apiUrl;

        //GET方式调用接口
        HttpGet httpGet = new HttpGet(url);

        CloseableHttpResponse response = null;
        try {
            //链接目标主机,接收目标主机返回的对象
            response = httpClient.execute(targetHost,httpGet,context);
        } catch (IOException e) {
            e.printStackTrace();
        }
        int status = response.getStatusLine().getStatusCode();

        if(status== HttpStatus.SC_OK){
            HttpEntity entity = response.getEntity();
            try {
                responseBody = EntityUtils.toString(entity);
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    //关闭连接
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return responseBody;
    }

    private static CloseableHttpClient getHttpClient() {
        RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create();
        ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory();
        //注册http协议,如果不需要http协议就不需要写。
        registryBuilder.register("http",plainSF);

        //以下是注册https协议,与http不同的是多了证书的校验
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            TrustStrategy trustStrategy = new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            };

            SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, trustStrategy).build();
            //允许全部的证书,这样访问的时候就不用去校验证书是否可用。
            LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            //注册https协议
            registryBuilder.register("https",sslsf);

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

        Registry<ConnectionSocketFactory> registry = registryBuilder.build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);

        return HttpClientBuilder.create().setConnectionManager(connManager).build();

    }
}

所依赖的jar为

 <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.5</version>
        </dependency>

  

posted @ 2016-11-16 15:53  zouminglan  阅读(5680)  评论(0编辑  收藏  举报