• 聊聊HttpClientBuilder


    本文主要研究一下HttpClientBuilder

    HttpClientBuilder

    httpclient-4.5.10-sources.jar!/org/apache/http/impl/client/HttpClientBuilder.java

    public class HttpClientBuilder {
    
        public static HttpClientBuilder create() {
            return new HttpClientBuilder();
        }
    
        protected HttpClientBuilder() {
            super();
        }
    
        public CloseableHttpClient build() {
            // Create main request executor
            // We copy the instance fields to avoid changing them, and rename to avoid accidental use of the wrong version
            PublicSuffixMatcher publicSuffixMatcherCopy = this.publicSuffixMatcher;
            if (publicSuffixMatcherCopy == null) {
                publicSuffixMatcherCopy = PublicSuffixMatcherLoader.getDefault();
            }
    
            HttpRequestExecutor requestExecCopy = this.requestExec;
            if (requestExecCopy == null) {
                requestExecCopy = new HttpRequestExecutor();
            }
            HttpClientConnectionManager connManagerCopy = this.connManager;
            if (connManagerCopy == null) {
                LayeredConnectionSocketFactory sslSocketFactoryCopy = this.sslSocketFactory;
                if (sslSocketFactoryCopy == null) {
                    final String[] supportedProtocols = systemProperties ? split(
                            System.getProperty("https.protocols")) : null;
                    final String[] supportedCipherSuites = systemProperties ? split(
                            System.getProperty("https.cipherSuites")) : null;
                    HostnameVerifier hostnameVerifierCopy = this.hostnameVerifier;
                    if (hostnameVerifierCopy == null) {
                        hostnameVerifierCopy = new DefaultHostnameVerifier(publicSuffixMatcherCopy);
                    }
                    if (sslContext != null) {
                        sslSocketFactoryCopy = new SSLConnectionSocketFactory(
                                sslContext, supportedProtocols, supportedCipherSuites, hostnameVerifierCopy);
                    } else {
                        if (systemProperties) {
                            sslSocketFactoryCopy = new SSLConnectionSocketFactory(
                                    (SSLSocketFactory) SSLSocketFactory.getDefault(),
                                    supportedProtocols, supportedCipherSuites, hostnameVerifierCopy);
                        } else {
                            sslSocketFactoryCopy = new SSLConnectionSocketFactory(
                                    SSLContexts.createDefault(),
                                    hostnameVerifierCopy);
                        }
                    }
                }
                @SuppressWarnings("resource")
                final PoolingHttpClientConnectionManager poolingmgr = new PoolingHttpClientConnectionManager(
                        RegistryBuilder.create()
                            .register("http", PlainConnectionSocketFactory.getSocketFactory())
                            .register("https", sslSocketFactoryCopy)
                            .build(),
                        null,
                        null,
                        dnsResolver,
                        connTimeToLive,
                        connTimeToLiveTimeUnit != null ? connTimeToLiveTimeUnit : TimeUnit.MILLISECONDS);
                if (defaultSocketConfig != null) {
                    poolingmgr.setDefaultSocketConfig(defaultSocketConfig);
                }
                if (defaultConnectionConfig != null) {
                    poolingmgr.setDefaultConnectionConfig(defaultConnectionConfig);
                }
                if (systemProperties) {
                    String s = System.getProperty("http.keepAlive", "true");
                    if ("true".equalsIgnoreCase(s)) {
                        s = System.getProperty("http.maxConnections", "5");
                        final int max = Integer.parseInt(s);
                        poolingmgr.setDefaultMaxPerRoute(max);
                        poolingmgr.setMaxTotal(2 * max);
                    }
                }
                if (maxConnTotal > 0) {
                    poolingmgr.setMaxTotal(maxConnTotal);
                }
                if (maxConnPerRoute > 0) {
                    poolingmgr.setDefaultMaxPerRoute(maxConnPerRoute);
                }
                connManagerCopy = poolingmgr;
            }
            ConnectionReuseStrategy reuseStrategyCopy = this.reuseStrategy;
            if (reuseStrategyCopy == null) {
                if (systemProperties) {
                    final String s = System.getProperty("http.keepAlive", "true");
                    if ("true".equalsIgnoreCase(s)) {
                        reuseStrategyCopy = DefaultClientConnectionReuseStrategy.INSTANCE;
                    } else {
                        reuseStrategyCopy = NoConnectionReuseStrategy.INSTANCE;
                    }
                } else {
                    reuseStrategyCopy = DefaultClientConnectionReuseStrategy.INSTANCE;
                }
            }
            ConnectionKeepAliveStrategy keepAliveStrategyCopy = this.keepAliveStrategy;
            if (keepAliveStrategyCopy == null) {
                keepAliveStrategyCopy = DefaultConnectionKeepAliveStrategy.INSTANCE;
            }
            AuthenticationStrategy targetAuthStrategyCopy = this.targetAuthStrategy;
            if (targetAuthStrategyCopy == null) {
                targetAuthStrategyCopy = TargetAuthenticationStrategy.INSTANCE;
            }
            AuthenticationStrategy proxyAuthStrategyCopy = this.proxyAuthStrategy;
            if (proxyAuthStrategyCopy == null) {
                proxyAuthStrategyCopy = ProxyAuthenticationStrategy.INSTANCE;
            }
            UserTokenHandler userTokenHandlerCopy = this.userTokenHandler;
            if (userTokenHandlerCopy == null) {
                if (!connectionStateDisabled) {
                    userTokenHandlerCopy = DefaultUserTokenHandler.INSTANCE;
                } else {
                    userTokenHandlerCopy = NoopUserTokenHandler.INSTANCE;
                }
            }
    
            String userAgentCopy = this.userAgent;
            if (userAgentCopy == null) {
                if (systemProperties) {
                    userAgentCopy = System.getProperty("http.agent");
                }
                if (userAgentCopy == null && !defaultUserAgentDisabled) {
                    userAgentCopy = VersionInfo.getUserAgent("Apache-HttpClient",
                            "org.apache.http.client", getClass());
                }
            }
    
            ClientExecChain execChain = createMainExec(
                    requestExecCopy,
                    connManagerCopy,
                    reuseStrategyCopy,
                    keepAliveStrategyCopy,
                    new ImmutableHttpProcessor(new RequestTargetHost(), new RequestUserAgent(userAgentCopy)),
                    targetAuthStrategyCopy,
                    proxyAuthStrategyCopy,
                    userTokenHandlerCopy);
    
            execChain = decorateMainExec(execChain);
    
            HttpProcessor httpprocessorCopy = this.httpprocessor;
            if (httpprocessorCopy == null) {
    
                final HttpProcessorBuilder b = HttpProcessorBuilder.create();
                if (requestFirst != null) {
                    for (final HttpRequestInterceptor i: requestFirst) {
                        b.addFirst(i);
                    }
                }
                if (responseFirst != null) {
                    for (final HttpResponseInterceptor i: responseFirst) {
                        b.addFirst(i);
                    }
                }
                b.addAll(
                        new RequestDefaultHeaders(defaultHeaders),
                        new RequestContent(),
                        new RequestTargetHost(),
                        new RequestClientConnControl(),
                        new RequestUserAgent(userAgentCopy),
                        new RequestExpectContinue());
                if (!cookieManagementDisabled) {
                    b.add(new RequestAddCookies());
                }
                if (!contentCompressionDisabled) {
                    if (contentDecoderMap != null) {
                        final List encodings = new ArrayList(contentDecoderMap.keySet());
                        Collections.sort(encodings);
                        b.add(new RequestAcceptEncoding(encodings));
                    } else {
                        b.add(new RequestAcceptEncoding());
                    }
                }
                if (!authCachingDisabled) {
                    b.add(new RequestAuthCache());
                }
                if (!cookieManagementDisabled) {
                    b.add(new ResponseProcessCookies());
                }
                if (!contentCompressionDisabled) {
                    if (contentDecoderMap != null) {
                        final RegistryBuilder b2 = RegistryBuilder.create();
                        for (final Map.Entry entry: contentDecoderMap.entrySet()) {
                            b2.register(entry.getKey(), entry.getValue());
                        }
                        b.add(new ResponseContentEncoding(b2.build()));
                    } else {
                        b.add(new ResponseContentEncoding());
                    }
                }
                if (requestLast != null) {
                    for (final HttpRequestInterceptor i: requestLast) {
                        b.addLast(i);
                    }
                }
                if (responseLast != null) {
                    for (final HttpResponseInterceptor i: responseLast) {
                        b.addLast(i);
                    }
                }
                httpprocessorCopy = b.build();
            }
            execChain = new ProtocolExec(execChain, httpprocessorCopy);
    
            execChain = decorateProtocolExec(execChain);
    
            // Add request retry executor, if not disabled
            if (!automaticRetriesDisabled) {
                HttpRequestRetryHandler retryHandlerCopy = this.retryHandler;
                if (retryHandlerCopy == null) {
                    retryHandlerCopy = DefaultHttpRequestRetryHandler.INSTANCE;
                }
                execChain = new RetryExec(execChain, retryHandlerCopy);
            }
    
            HttpRoutePlanner routePlannerCopy = this.routePlanner;
            if (routePlannerCopy == null) {
                SchemePortResolver schemePortResolverCopy = this.schemePortResolver;
                if (schemePortResolverCopy == null) {
                    schemePortResolverCopy = DefaultSchemePortResolver.INSTANCE;
                }
                if (proxy != null) {
                    routePlannerCopy = new DefaultProxyRoutePlanner(proxy, schemePortResolverCopy);
                } else if (systemProperties) {
                    routePlannerCopy = new SystemDefaultRoutePlanner(
                            schemePortResolverCopy, ProxySelector.getDefault());
                } else {
                    routePlannerCopy = new DefaultRoutePlanner(schemePortResolverCopy);
                }
            }
    
            // Optionally, add service unavailable retry executor
            final ServiceUnavailableRetryStrategy serviceUnavailStrategyCopy = this.serviceUnavailStrategy;
            if (serviceUnavailStrategyCopy != null) {
                execChain = new ServiceUnavailableRetryExec(execChain, serviceUnavailStrategyCopy);
            }
    
            // Add redirect executor, if not disabled
            if (!redirectHandlingDisabled) {
                RedirectStrategy redirectStrategyCopy = this.redirectStrategy;
                if (redirectStrategyCopy == null) {
                    redirectStrategyCopy = DefaultRedirectStrategy.INSTANCE;
                }
                execChain = new RedirectExec(execChain, routePlannerCopy, redirectStrategyCopy);
            }
    
            // Optionally, add connection back-off executor
            if (this.backoffManager != null && this.connectionBackoffStrategy != null) {
                execChain = new BackoffStrategyExec(execChain, this.connectionBackoffStrategy, this.backoffManager);
            }
    
            Lookup authSchemeRegistryCopy = this.authSchemeRegistry;
            if (authSchemeRegistryCopy == null) {
                authSchemeRegistryCopy = RegistryBuilder.create()
                    .register(AuthSchemes.BASIC, new BasicSchemeFactory())
                    .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
                    .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
                    .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
                    .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory())
                    .build();
            }
            Lookup cookieSpecRegistryCopy = this.cookieSpecRegistry;
            if (cookieSpecRegistryCopy == null) {
                cookieSpecRegistryCopy = CookieSpecRegistries.createDefault(publicSuffixMatcherCopy);
            }
    
            CookieStore defaultCookieStore = this.cookieStore;
            if (defaultCookieStore == null) {
                defaultCookieStore = new BasicCookieStore();
            }
    
            CredentialsProvider defaultCredentialsProvider = this.credentialsProvider;
            if (defaultCredentialsProvider == null) {
                if (systemProperties) {
                    defaultCredentialsProvider = new SystemDefaultCredentialsProvider();
                } else {
                    defaultCredentialsProvider = new BasicCredentialsProvider();
                }
            }
    
            List closeablesCopy = closeables != null ? new ArrayList(closeables) : null;
            if (!this.connManagerShared) {
                if (closeablesCopy == null) {
                    closeablesCopy = new ArrayList(1);
                }
                final HttpClientConnectionManager cm = connManagerCopy;
    
                if (evictExpiredConnections || evictIdleConnections) {
                    final IdleConnectionEvictor connectionEvictor = new IdleConnectionEvictor(cm,
                            maxIdleTime > 0 ? maxIdleTime : 10, maxIdleTimeUnit != null ? maxIdleTimeUnit : TimeUnit.SECONDS,
                            maxIdleTime, maxIdleTimeUnit);
                    closeablesCopy.add(new Closeable() {
    
                        @Override
                        public void close() throws IOException {
                            connectionEvictor.shutdown();
                            try {
                                connectionEvictor.awaitTermination(1L, TimeUnit.SECONDS);
                            } catch (final InterruptedException interrupted) {
                                Thread.currentThread().interrupt();
                            }
                        }
    
                    });
                    connectionEvictor.start();
                }
                closeablesCopy.add(new Closeable() {
    
                    @Override
                    public void close() throws IOException {
                        cm.shutdown();
                    }
    
                });
            }
    
            return new InternalHttpClient(
                    execChain,
                    connManagerCopy,
                    routePlannerCopy,
                    cookieSpecRegistryCopy,
                    authSchemeRegistryCopy,
                    defaultCookieStore,
                    defaultCredentialsProvider,
                    defaultRequestConfig != null ? defaultRequestConfig : RequestConfig.DEFAULT,
                    closeablesCopy);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328

    HttpClientBuilder提供了静态方法create用于创建builder,其build方法用于创建CloseableHttpClient,它主要是构建ClientExecChain(HttpRequestExecutor、HttpClientConnectionManager、ConnectionReuseStrategy、ConnectionKeepAliveStrategy、AuthenticationStrategy、UserTokenHandler)、ProtocolExec(ClientExecChain、HttpProcessor)、RetryExec(ClientExecChain、HttpRequestRetryHandler)、RedirectExec(HttpRoutePlanner、ServiceUnavailableRetryStrategy、RedirectStrategy)、BackoffStrategyExec;最后构建的是InternalHttpClient

    SSLContext

    org/apache/http/ssl/SSLContexts.java
    对于sslContext不为null的则创建SSLConnectionSocketFactory(sslContext, supportedProtocols, supportedCipherSuites, hostnameVerifierCopy),为null的话,则通过SSLContexts.createDefault()来创建默认的SSLContext

    public static SSLContext createDefault() throws SSLInitializationException {
            try {
                final SSLContext sslContext = SSLContext.getInstance(SSLContextBuilder.TLS);
                sslContext.init(null, null, null);
                return sslContext;
            } catch (final NoSuchAlgorithmException ex) {
                throw new SSLInitializationException(ex.getMessage(), ex);
            } catch (final KeyManagementException ex) {
                throw new SSLInitializationException(ex.getMessage(), ex);
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    HostnameVerifier

    若hostnameVerifier为null,则创建默认的DefaultHostnameVerifier

    public DefaultHostnameVerifier(final PublicSuffixMatcher publicSuffixMatcher) {
            this.publicSuffixMatcher = publicSuffixMatcher;
        }
    
        public DefaultHostnameVerifier() {
            this(null);
        }
    
        @Override
        public boolean verify(final String host, final SSLSession session) {
            try {
                final Certificate[] certs = session.getPeerCertificates();
                final X509Certificate x509 = (X509Certificate) certs[0];
                verify(host, x509);
                return true;
            } catch (final SSLException ex) {
                if (log.isDebugEnabled()) {
                    log.debug(ex.getMessage(), ex);
                }
                return false;
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    PoolingHttpClientConnectionManager

    org/apache/http/impl/conn/PoolingHttpClientConnectionManager.java

    @Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL)
    public class PoolingHttpClientConnectionManager
        implements HttpClientConnectionManager, ConnPoolControl, Closeable {
    
        private final ConfigData configData;
        private final CPool pool;
        private final HttpClientConnectionOperator connectionOperator;
        private final AtomicBoolean isShutDown;
    
        public PoolingHttpClientConnectionManager(
            final HttpClientConnectionOperator httpClientConnectionOperator,
            final HttpConnectionFactory connFactory,
            final long timeToLive, final TimeUnit timeUnit) {
            super();
            this.configData = new ConfigData();
            this.pool = new CPool(new InternalConnectionFactory(
                    this.configData, connFactory), 2, 20, timeToLive, timeUnit);
            this.pool.setValidateAfterInactivity(2000);
            this.connectionOperator = Args.notNull(httpClientConnectionOperator, "HttpClientConnectionOperator");
            this.isShutDown = new AtomicBoolean(false);
        }
    
        @Override
        protected void finalize() throws Throwable {
            try {
                shutdown();
            } finally {
                super.finalize();
            }
        }
    
        @Override
        public void close() {
            shutdown();
        }
    
        //......
    }    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    PoolingHttpClientConnectionManager实现了HttpClientConnectionManager、ConnPoolControl、Closeable接口,它使用了CPool作为连接池来管理连接,默认的maxPerRoute为2,maxTotal为20

    小结

    apache的httpclient的HttpClientBuilder提供了构建CloseableHttpClient的方法,它提供了设置sslContext的方法,如果没有设置则通过SSLContexts.createDefault()来创建默认的SSLContext,若hostnameVerifier为null,则创建默认的DefaultHostnameVerifier,其默认会创建HttpClientConnectionManager,使用的是maxPerRoute为2,maxTotal为20的连接池。

  • 相关阅读:
    力扣(LeetCode)816. 模糊坐标(C++)
    算法67-链表相交问题
    算法竞赛进阶指南 基本算法 0x07 贪心
    B031-网络编程 Socket Http TomCat
    学习MATLAB
    Elasticsearch 聚合检索 (分组统计)
    8. String to Integer (atoi)
    组件之间的数据共享(常用)
    暑假leetcode剑指offer每日一题打卡-第二十天-剑指 Offer 49. 丑数(middle)
    2024.3.11 - DAY05_JAVA高级
  • 原文地址:https://blog.csdn.net/hello_ejb3/article/details/133554545