简体   繁体   中英

How to set bufferSize with Apache HttpClient5?

I would like to migrate to Apache HttpClient 5 for one of the project I am working on. However I am facing a small issue:

With HttpClient 4 we were able to set the bufferSize by setting the defaultConnectionConfig:

HttpClientBuilder.create().setDefaultConnectionConfig(ConnectionConfig.custom().setBufferSize(myBufferSize).build());

Unfortunately I am not able to find that option with HttpClient 5. Is it still possible with the new version or do I need to stick with HttpClient 4? Thanks !

Referring to HttpClient configuration provided inHttpClient Examples (Classic) , it can be configured, but with more steps:

import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.io.BasicHttpClientConnectionManager;
import org.apache.hc.client5.http.impl.io.ManagedHttpClientConnectionFactory;
import org.apache.hc.client5.http.io.ManagedHttpClientConnection;
import org.apache.hc.client5.http.socket.ConnectionSocketFactory;
import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.URIScheme;
import org.apache.hc.core5.http.config.Http1Config;
import org.apache.hc.core5.http.config.Registry;
import org.apache.hc.core5.http.config.RegistryBuilder;
import org.apache.hc.core5.http.io.HttpConnectionFactory;

public class CustomClientConfig {
    public static void main(String[] args) {
        int bufferSize = 0;
        Http1Config customHttpConfig = Http1Config.custom().setBufferSize(bufferSize).build();
        HttpConnectionFactory<ManagedHttpClientConnection> connectionFactory =
                ManagedHttpClientConnectionFactory.builder().
                        http1Config(customHttpConfig).build();
        BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(
                getDefaultRegistry(), connectionFactory);
        CloseableHttpClient httpclient = HttpClientBuilder.create()
                .setConnectionManager(connectionManager).build();
    }

    // copy from BasicHttpClientConnectionManager
    private static Registry<ConnectionSocketFactory> getDefaultRegistry() {
        return RegistryBuilder.<ConnectionSocketFactory>create()
                .register(URIScheme.HTTP.id, PlainConnectionSocketFactory.getSocketFactory())
                .register(URIScheme.HTTPS.id, SSLConnectionSocketFactory.getSocketFactory())
                .build();
    }

}

You may also want to take a look on the migration guide

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM