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

com.aliyun.datahub.client.http.common.HttpRequestBuilder Maven / Gradle / Ivy

The newest version!
package com.aliyun.datahub.client.http.common;

import com.aliyun.datahub.client.http.HttpClient;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public abstract class HttpRequestBuilder {
    private static int maxIdleConnections = 3;
    private static ConnectionPool connectionPool;
    private static Map clientMap = new HashMap<>();

    public static int getMaxIdleConnections() {
        return maxIdleConnections;
    }

    public static void setMaxIdleConnections(int maxIdleConnections) {
        HttpRequestBuilder.maxIdleConnections = maxIdleConnections;
    }

    public static HttpRequest createRequest(String endpoint, HttpRequestConfig config) {
        return createRequest(endpoint, config, new HttpInterceptor());
    }

    public static HttpRequest createRequest(String endpoint, HttpRequestConfig config, HttpInterceptor interceptor) {
        if (!endpoint.startsWith("http")) {
            endpoint = "http://" + endpoint;
        }

        OkHttpClient client = clientMap.get(config);
        if (client == null) {
            synchronized (HttpRequestBuilder.class) {
                client = clientMap.get(config);
                if (client == null) {
                    client = createClient(config);
                    clientMap.put(config, client);
                }
            }
        }
        return new HttpRequest(client)
                .endpoint(endpoint)
                .interceptor(interceptor);
    }

    private static OkHttpClient createClient(HttpRequestConfig config) {
        if (connectionPool == null) {
            connectionPool = new ConnectionPool(maxIdleConnections, 60, TimeUnit.SECONDS);
        }
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectionPool(connectionPool)
                .readTimeout(config.getReadTimeout(), TimeUnit.MILLISECONDS)
                .writeTimeout(config.getReadTimeout(), TimeUnit.MILLISECONDS)
                .connectTimeout(config.getConnTimeout(), TimeUnit.MILLISECONDS)
                .sslSocketFactory(HttpClient.sslSocketFactory(), HttpClient.x509TrustManager());

        return builder.build();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy