有人可以指向权威的示例,演示如何使用Proxy进行身份验证。
我的搜索显示不一定使用ver的各种示例。 4.3.6因而混淆。
我遇到了以下两种方法。我不想为每个请求设置代理和凭据,因此想知道这里的最佳做法是什么?此外,我必须确保这适用于Basic,Digest和NTLM方案。
方法1:
// Create client and set credential provider
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build();
// Every request is set the with proxy settings
RequestConfig config = RequestConfig.custom()
.setProxy(proxy)
.build();
HttpGet httpget = new HttpGet("/");
httpget.setConfig(config);
方法2:
HttpHost proxyHost = new HttpHost(proxyServer, proxyPort);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyHost);
HttpClientBuilder clientBuilder = HttpClients.custom()
.setConnectionManager(connectionManager);
clientBuilder.setRoutePlanner(routePlanner);
client = clientBuilder.build();
// Where and how to set credentials as best practice ?
我肯定会对这一点感到懊悔,但到目前为止,我已经想了太多,因此请求一些帮助。 感谢,
答案 0 :(得分:1)
Ok这是我最终做的并解决了用例。
// Method that returns HTTP Client that can be re-used for various GET/POST/... calls
static CloseableHttpClient makeHttpClient(...) throws IOException {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
// Default MAX connections per route
connectionManager.setDefaultMaxPerRoute(...);
// MAX total connections
connectionManager.setMaxTotal(...);
HttpClientBuilder clientBuilder = HttpClients.custom()
.setConnectionManager(connectionManager);
// Set proxy if needed
HttpHost proxyHost = new HttpHost(theProxyServer, port);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyHost);
clientBuilder.setRoutePlanner(routePlanner);
// Select and configure the properties you are interested in
RequestConfig config = RequestConfig.custom()
.setProxy(proxyHost)
.setRedirectsEnabled(true)
.setMaxRedirects(5)
.setConnectTimeout(100 * 1000)
.setConnectionRequestTimeout(300 * 1000)
.setSocketTimeout(300 * 1000)
.build();
// set proxy authentication as needed
CredentialsProvider credentialProvider = new BasicCredentialsProvider();
// set NTLM/basic/digest credentials
credentialProvider.setCredentials(...)
....
clientBuilder.setDefaultCredentialsProvider(credentialProvider);
clientBuilder.setDefaultRequestConfig(config);
// Now build and return the client
return clientBuilder.build();
}
现在在其他地方使用此客户端来执行HTTP操作。
// get HTTP client
makeHttpClient(...)
// get payload
HttpPost postMethod = new HttpPost(url);
postMethod.setHeader(CONTENT_TYPE, CONTENT_TYPE_JSON);
postMethod.setEntity(payload);
try {
response = client.execute(postMethod);
...
} catch(...) { ... }
这有助于创建具有所有所需特征的HTTP客户端,这些特性可以重复用于不同位置的各种HTTP操作。