Proxy Authentication With Fluent API Request?

痞子三分冷 提交于 2019-12-10 17:07:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!