问题
I am currently using a Get Request with proxy information:
String result1 = Request.Get("_http://somehost/")
.version(HttpVersion.HTTP_1_1)
.connectTimeout(1000)
.socketTimeout(1000)
.viaProxy(new HttpHost("myproxy", 8080))
.execute().returnContent().asString();
The result is a "Proxy Authentication Required" error. I believe a username and password is required from the server making the request? If so, how do I add that detail? I have never used the Fluent API before.
回答1:
You need a CredentialsProvider
.
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(username, password));
final HttpPost httppost = new HttpPost(uri);
httppost.setConfig(RequestConfig.custom().setProxy(proxy).build());
String line = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build() .execute(httppost).getStatusLine());
Also, there was a bug in 4.3.1 that impacted authentication. It is fixed in 4.3.2. https://issues.apache.org/jira/browse/HTTPCLIENT-1435
回答2:
Here is an example using the Fluent API. The executor can be used to specify credentials for the proxy.
HttpHost proxyHost = new HttpHost("myproxy", 8080);
Executor executor = Executor.newInstance()
.auth(proxyHost, "username", "password");
String result1 = executor.execute(Request.Get("_http://somehost/")
.viaProxy(proxyHost))
.returnContent()
.asString();
回答3:
Executor executor = Executor.newInstance()
.auth(new HttpHost("myproxy", 8080), "username", "password")
.authPreemptive(new HttpHost("myproxy", 8080));
Response response = executor.execute(<your reques>);
来源:https://stackoverflow.com/questions/15482903/proxy-authentication-with-fluent-api-request