使用HTTPClientParams for HttpClient 4.5

时间:2018-01-12 05:06:30

标签: httpclient apache-httpclient-4.x

我有一个使用HTTPClientParams的HttpClient 3.x代码。

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);

我已经验证了对于HTTPClient 4.5,没有HTTPParam方法。我怎样才能升级呢?还有其他选择吗?

1 个答案:

答案 0 :(得分:1)

请查看RequestConfig课程

此代码应与上面的代码大致相同

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));
}