live2learn
live2learn

Reputation: 911

Using HTTPClientParams for HttpClient 4.5

I have a code with HttpClient 3.x which uses HTTPClientParams.

HttpClientParams params = new HttpClientParams();
params.setVersion(HttpVersion.HTTP_1_1);
params.setContentCharset(ENCODING);
try {
        URI uri = new URI(some-resource);
        int port = uri.getPort();
        Protocol protocol = null;
        if(port == -1){
            if(uri.getScheme().compareToIgnoreCase("http") == 0){
                port = 80;
                protocol = Protocol.getProtocol("http");
            }
            else if(uri.getScheme().compareToIgnoreCase("https") == 0){
                port = 443;
                protocol = Protocol.getProtocol("https");
            }
        }
        Protocol.registerProtocol(uri.getScheme(), protocol);
        HttpConnectionManager manager = new SimpleHttpConnectionManager();
        HttpClient client = new HttpClient(manager);
        client.setParams(params);

I have verified that for HTTPClient 4.5 there are not HTTPParam method. How can I upgrade the same? Are there any alternatives?

Upvotes: 0

Views: 871

Answers (1)

ok2c
ok2c

Reputation: 27538

Please have a look at RequestConfig class

This code should be roughly equivalent to your code above

CloseableHttpClient client = HttpClientBuilder.create()
        .setConnectionManager(new BasicHttpClientConnectionManager())
        .setDefaultRequestConfig(RequestConfig
                .custom()
                // Add custom request parameters
                .build())
        .build();
URI uri = new URI(some - resource);
HttpGet httpGet = new HttpGet(uri);
httpGet.setProtocolVersion(HttpVersion.HTTP_1_1);
try (CloseableHttpResponse response1 = client.execute(httpGet)) {
    EntityUtils.toString(response1.getEntity(), Charset.forName(ENCODING));
}

Upvotes: 2

Related Questions