如何在 Apache HttpClient 4.3+ 中设置默认 HttpHost 目标? [英] How does one set Default HttpHost Target in Apache HttpClient 4.3+?

查看:80
本文介绍了如何在 Apache HttpClient 4.3+ 中设置默认 HttpHost 目标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Apache HttpClient 4.2 中,可以创建一个 DefaultHttpClient 并设置一个主机,以便那些进行 execute 调用的人不必在输入请求 URI 中提供主机信息,即:

In Apache HttpClient 4.2 one could create a DefaultHttpClient and set a host such that those making an execute call would not have to provide the host information in the input request URI, i.e.:

HttpHost targetHost = new HttpHost(host, port, secure ? "https" : "http");      
DefaultHttpClient defaultHttp = new DefaultHttpClient(connectionManager);
defaultHttp.getParams().setParameter(ClientPNames.DEFAULT_HOST, targetHost);

我承认这个策略看起来很尴尬,我继承了这段代码:).我相信在 4.2 中有更好的方法来做到这一点.

I do admit this strategy appears very awkward, I inherited this code :). I'm sure there's an even better way to do this in 4.2.

我想升级到 4.3 并注意到 DefaultHttpClientClientPNames 现在都被弃用了,取而代之的是 HttpClientBuilderRequestConfig 分别.但是我找不到这样的方法来定义带有 RequestConfig 的默认目标.

I'm looking to upgrade to 4.3 and noticed that DefaultHttpClient and ClientPNames are now both deprecated in favor of HttpClientBuilder and RequestConfig respectively. However I can find no such way to define a default target with RequestConfig.

Documentation for execute 确实引用了该输入目标参数可以接受空值,所以我确定还有一种方法可以促进这一点,但我正在努力解决这个问题:

Documentation for execute does reference that that input target parameter can accept null, so I'm sure there is still a way to facilitate this, but I'm struggling to figure this out:

target - 请求的目标主机.如果实现仍然可以确定路由,例如到默认目标或通过检查请求,则它们可以接受 null.

target - the target host for the request. Implementations may accept null if they can still determine a route, for example to a default target or by inspecting the request.

推荐答案

这应该可以解决问题

HttpRoutePlanner rp = new DefaultRoutePlanner(DefaultSchemePortResolver.INSTANCE) {

    @Override
    public HttpRoute determineRoute(
            final HttpHost host,
            final HttpRequest request,
            final HttpContext context) throws HttpException {
        HttpHost target = host != null ? host : new HttpHost("some.default.host");
        return super.determineRoute(target, request, context);
    }
};

CloseableHttpClient client = HttpClients.custom()
        .setRoutePlanner(rp)
        .build();

这篇关于如何在 Apache HttpClient 4.3+ 中设置默认 HttpHost 目标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆