http client 使用proxy 加request body 和 request headers 调用API返回access token的方法

package com.example.demozhw2;


import org.apache.commons.codec.binary.Base64;
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.net.URI;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyHttpClient {



    public static void main(String[] args) throws Exception{
        CloseableHttpClient httpClient = createSSLClientDefault3();//HttpClients.custom().setDefaultCredentialsProvider(provider).setSSLSocketFactory(sslsf).build();
        HttpHost proxy = new HttpHost("intpxy1.hk.hsbc",8080,"http");
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setProxy(proxy)
                .build();
        CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials("43919871", "Wanke608"));
        //httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();
        //httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).setDefaultCredentialsProvider(provider).build();
        String url = "https://uat.questnet.sg/API/OAuth2/v1/Token";
        URI urlObj = new URI(url.trim());
        HttpPost httpPost= new HttpPost(urlObj);
        //System.setProperty("jsse.enableSNIExtension", "false");
        Map map = new HashMap<>();
        map.put("grant_type","client_credentials");
        map.put("scope","Order Collect");
        map.put("client_id","e768c1d84eb3468588acf2633bb91fa8");
        map.put("client_secret","017ec96c6d6e4aca84e3a13bd9d7690333501819d0a6422c8ef0f4aae1bbdfcc");
        List pairs = new ArrayList();
        for (Map.Entry entry : map.entrySet()) {
            pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
        //httpPost.addHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString(("e768c1d84eb3468588acf2633bb91fa8" + ":" + "017ec96c6d6e4aca84e3a13bd9d7690333501819d0a6422c8ef0f4aae1bbdfcc").getBytes()));
        httpPost.addHeader("Authorization", getHeader());
        httpPost.addHeader("Content-Type","application/x-www-form-urlencoded");
        //httpPost.addHeader("client_id","e768c1d84eb3468588acf2633bb91fa8");
        //httpPost.addHeader("client_secret","017ec96c6d6e4aca84e3a13bd9d7690333501819d0a6422c8ef0f4aae1bbdfcc");
        String result = "";
        HttpResponse httpResponse = null;
        HttpEntity entity = null;
        httpResponse = httpClient.execute(httpPost);
        entity = httpResponse.getEntity();
        if( entity != null ){
            result = EntityUtils.toString(entity);
        }

        System.out.println("zhw***"+result);
    }

    private static CloseableHttpClient buildSSLCloseableHttpClient()
            throws Exception {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
                new TrustStrategy() {
                    // 信任所有
                    @Override
                    public boolean isTrusted(X509Certificate[] chain,
                                             String authType) throws CertificateException {
                        return true;
                    }
                }).build();
        // ALLOW_ALL_HOSTNAME_VERIFIER:这个主机名验证器基本上是关闭主机名验证的,实现的是一个空操作,并且不会抛出javax.net.ssl.SSLException异常。
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    }

    public static CloseableHttpClient createSSLClientDefault(){

        try {
            //SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            // 在JSSE中,证书信任管理器类就是实现了接口X509TrustManager的类。我们可以自己实现该接口,让它信任我们指定的证书。
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            //信任所有
            X509TrustManager x509mgr = new X509TrustManager() {

                //  该方法检查客户端的证书,若不信任该证书则抛出异常
                public void checkClientTrusted(X509Certificate[] xcs, String string) {
                }
                //   该方法检查服务端的证书,若不信任该证书则抛出异常
                public void checkServerTrusted(X509Certificate[] xcs, String string) {
                }
                //  返回受信任的X509证书数组。
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[] { x509mgr }, null);
            创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            //  HttpsURLConnection对象就可以正常连接HTTPS了,无论其证书是否经权威机构的验证,只要实现了接口X509TrustManager的类MyX509TrustManager信任该证书。
            HttpHost proxy = new HttpHost("intpxy1.hk.hsbc",8080,"http");
            CredentialsProvider provider = new BasicCredentialsProvider();
            provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials("43919871", "Wanke608"));
            return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(provider).build();


        } catch (KeyManagementException e) {

            e.printStackTrace();

        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace();

        } catch (Exception e) {

            e.printStackTrace();

        }

        // 创建默认的httpClient实例.
        return  HttpClients.createDefault();

    }

    public static CloseableHttpClient createSSLClientDefault2() {
        try {
            //使用 loadTrustMaterial() 方法实现一个信任策略,信任所有证书
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // 信任所有
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            //NoopHostnameVerifier类:  作为主机名验证工具,实质上关闭了主机名验证,它接受任何
            //有效的SSL会话并匹配到目标主机。
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
            HttpHost proxy = new HttpHost("intpxy1.hk.hsbc",8080,"https");
            CredentialsProvider provider = new BasicCredentialsProvider();
            provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials("43919871", "Wanke608"));
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();

    }

    private static CloseableHttpClient createSSLClientDefault3() {
        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, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            HttpHost proxy = new HttpHost("intpxy1.hk.hsbc",8080,"http");
            RequestConfig defaultRequestConfig = RequestConfig.custom()
                    .setProxy(proxy)
                    .build();
            CredentialsProvider provider = new BasicCredentialsProvider();
            provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials("43919871", "Wanke608"));
            CredentialsProvider provider2 = new BasicCredentialsProvider();
            provider2.setCredentials(new AuthScope("uat.questnet.sg", 8080),
                    new UsernamePasswordCredentials("e768c1d84eb3468588acf2633bb91fa8", "017ec96c6d6e4aca84e3a13bd9d7690333501819d0a6422c8ef0f4aae1bbdfcc"));
//            CredentialsProvider credsProvider = new BasicCredentialsProvider();
//            credsProvider.setCredentials(AuthScope.ANY,
//                    new UsernamePasswordCredentials("e768c1d84eb3468588acf2633bb91fa8", "017ec96c6d6e4aca84e3a13bd9d7690333501819d0a6422c8ef0f4aae1bbdfcc"));
            //HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).setDefaultCredentialsProvider(provider).build();
            CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(defaultRequestConfig).setDefaultCredentialsProvider(provider).build();
            //CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(defaultRequestConfig).build();
            System.out.println("1.走的这里...");
            return client;
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("2.走的这里...");
        return HttpClients.createDefault();
    }

    private static String getHeader() {
        String auth = "e768c1d84eb3468588acf2633bb91fa8" + ":" + "017ec96c6d6e4aca84e3a13bd9d7690333501819d0a6422c8ef0f4aae1bbdfcc";
        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
        String authHeader = "Basic " + new String(encodedAuth);
        return authHeader;
    }

}

你可能感兴趣的:(java,spring)