除了目标站点凭据之外,如何在 Apache httpclient 中指定代理身份验证凭据?

How to specify proxy authentication credentials in Apache httpclient in addition to the target site credentials?

我需要使用 Apache httpclient 通过代理连接到远程网站。 代理和网站都使用不同 logins/passwords 的基本身份验证。 我有以下代码通过代理连接到远程站点。 但我不知道如何在那里添加代理凭据。 有什么想法吗?

...
    this.proxy = RequestConfig.custom()
            .setProxy(new HttpHost(host, port, scheme)).build();
    this.proxyEnabled = true;
...
    CredentialsProvider credsProvider = new BasicCredentialsProvider();

    Credentials creds = new UsernamePasswordCredentials(this.username,
            this.password);

    if (debug) {
        credsProvider.setCredentials(AuthScope.ANY, creds);
    } else {
        credsProvider.setCredentials(new AuthScope(this.getHost(), -1),
                creds);
    }

    CloseableHttpClient client = HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider).build();


    try {

        if (proxyEnabled) {
            httpRequest.setConfig(this.proxy);

        }

        CloseableHttpResponse response = client.execute(httpRequest);
...

一个CredentialsProvider可以管理多个AuthScope,参见例如BasicCredentialsProvider 中的实现(注意对 credMap.put() 的调用):

@Override
public void setCredentials(
        final AuthScope authscope,
        final Credentials credentials) {
    Args.notNull(authscope, "Authentication scope");
    credMap.put(authscope, credentials);
}

因此,只需为每个范围调用 setCredentials() 即可:

CredentialsProvider credsProvider = new BasicCredentialsProvider();

AuthScope siteScope = new AuthScope(siteHost, sitePort);
Credentials siteCreds = new UsernamePasswordCredentials(siteUsername, sitePassword);
credsProvider.setCredentials(siteScope, siteCreds);

AuthScope proxyScope = new AuthScope(proxyHost, proxyPort);
Credentials proxyCreds = new UsernamePasswordCredentials(proxyUsername, proxyPassword);
credsProvider.setCredentials(proxyScope, proxyCreds);