All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.com.antcloud.api.acapi.AntCloudHttpClient Maven / Gradle / Ivy

Go to download

Ant Fin Tech API SDK For Java Copyright (c) 2015-present Alipay.com, https://www.alipay.com

The newest version!
/*
 * Copyright (c) 2015-present Alipay.com, https://www.alipay.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.com.antcloud.api.acapi;

import cn.com.antcloud.api.common.ClientException;
import cn.com.antcloud.api.utils.IOUtils;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
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.methods.HttpUriRequest;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
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.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;

import javax.net.ssl.SSLContext;
import java.io.Closeable;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class AntCloudHttpClient implements Closeable {

    private HttpConfig httpConfig;
    private CloseableHttpClient httpClient;
    private PoolingHttpClientConnectionManager connectionManager;

    public AntCloudHttpClient(final HttpConfig config) {
        this.httpConfig = config;
//        HttpClientBuilder clientBuilder = HttpClientBuilder.create();
//        HttpClientBuilder builder = TracerHttpClientBuilder.clientBuilderForSofaRest(clientBuilder);
        HttpClientBuilder builder = HttpClientBuilder.create();

        RequestConfig defaultConfig = RequestConfig.custom()
                .setConnectTimeout(config.getConnectionTimeoutMillis())
                .setSocketTimeout(config.getReadTimeoutMillis())
                .setConnectionRequestTimeout(config.getWriteTimeoutMillis())
                .build();
        builder.setDefaultRequestConfig(defaultConfig);

        // 配置代理
        this.configProxy(config, builder);

        RegistryBuilder socketFactoryRegistryBuilder = RegistryBuilder.create();
        socketFactoryRegistryBuilder.register("http", new PlainConnectionSocketFactory());
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // trust all
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
            socketFactoryRegistryBuilder.register("https", connectionFactory);
        } catch (Exception e) {
            throw new ClientException("SDK.InitFailed, Init https with SSL certs ignore failed", e);
        }

        // 连接池
        if (config.isEnableConnectionPools()) {
            connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistryBuilder.build());
            connectionManager.setMaxTotal(config.getMaxRequests());
            connectionManager.setDefaultMaxPerRoute(config.getMaxRequestsPerHost());

            builder.setConnectionManager(connectionManager);
            ApacheIdleConnectionCleaner.registerConnectionManager(connectionManager, config.getMaxIdleTimeMillis());
        }

        // keepAlive
        if (config.getKeepAliveDurationMillis() > 0) {
            builder.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
                @Override
                public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                    long duration = DefaultConnectionKeepAliveStrategy.INSTANCE.getKeepAliveDuration(response, context);

                    if (duration > 0 && duration < config.getKeepAliveDurationMillis()) {
                        return duration;
                    } else {
                        return config.getKeepAliveDurationMillis();
                    }
                }
            });
        }

        httpClient = builder.disableAutomaticRetries().build();
    }

    public HttpConfig getHttpConfig() {
        return httpConfig;
    }

    public HttpResponse invoke(HttpUriRequest request) throws IOException {
        return httpClient.execute(request);
    }

    /**
     * 配置代理
     *
     * @param config
     * @param builder
     */
    private void configProxy(HttpConfig config, HttpClientBuilder builder) {
        if (!StringUtils.isEmpty(config.getProxyHost()) && config.getProxyPort() != null) {
            HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort(), "http");
            builder.setProxy(proxy);

            // ~~ 配置代理服务器的用户名和密码
            if (!StringUtils.isEmpty(config.getProxyUsername()) && !StringUtils.isEmpty(config.getProxyPassword())) {
                CredentialsProvider provider = new BasicCredentialsProvider();
                provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
                builder.setDefaultCredentialsProvider(provider);
            }
        }
    }

    @Override
    public void close() throws IOException {
        ApacheIdleConnectionCleaner.removeConnectionManager(connectionManager);
        connectionManager.shutdown();
        IOUtils.closeQuietly(httpClient);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy