使用 httpClient 向 resttemplate 添加代理信息和基本身份验证

Dil*_*anD 4 proxy spring basic-authentication resttemplate

我的开发环境在代理后面,所以我需要将代理信息设置为其余模板,当我使用 HttpComponentsClientHttpRequestFactory 并在 httpClient 中设置代理设置并将其设置在模板中时,这一切都很好。

但是现在我有一个需要基本身份验证的休息服务。要设置基本身份验证凭据,我需要在其余模板的 httpClient 中设置它们。但是我看到 httpClient 中的 getparams 方法已被弃用,所以我不能只更新模板中的现有客户端,如果我创建一个新的 httpclient 对象,我将覆盖在应用程序引导期间设置的代理信息。

那么有什么方法可以从其余模板中提取 httpClient 并更新它吗?或者有没有其他方法可以解决这个问题?

谢谢。

fat*_*ddy 5

配置httpClient如下:

HttpHost target = new HttpHost("hostname", 80, "http");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
        new AuthScope(target.getHostName(), target.getPort()),
        new UsernamePasswordCredentials("user", "passwd"));

HttpHost proxy = new HttpHost("proxy", 12345);
CloseableHttpClient httpclient = HttpClients.custom()
        .setProxy(proxy)
        .setDefaultCredentialsProvider(credsProvider).build();

HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpclient);

RestTemplate restTemplate = new RestTemplate(requestFactory);
Run Code Online (Sandbox Code Playgroud)

另请参阅HttpClient 示例