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>

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM