因此,我正在使用NTLM身份验证的公司代理下工作。可以正确检测到身份验证,并且我可以访问需要通过代理访问的不同API。
当我尝试访问需要基本身份验证的API端点( GET请求)时,出现问题。每当我尝试通过代码访问它时,都会得到未经授权的401,并且可以在标题中看到“ WWW-Authenticate:Basic realm =“ Realm”。
我尝试了各种不同的方法,但是最终结果总是相同的。
我尝试直接在URI中设置用户名和密码:
HttpGet request = new HttpGet(https://username:password@APIHost.com/end/point)
我已经尝试使用基本凭据提供程序:
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
我尝试在请求中手动添加Base64授权标头:
request.addHeader("Authorization", "Basic .........................");
另外,请注意,我可以使用PostMan甚至是网络浏览器通过代理访问此端点。
编辑
我已经注意到,实际上,如果我连续两次运行HttpRequest(使用相同的SessionID等),则第一个将以401失败,但是第二个请求实际上将成功。知道为什么会这样吗?我在想代理可能没有转发基本身份验证...
我尝试了更多的事情,但是到现在为止一切都没有用。
任何帮助将不胜感激! :)
答案 0 :(得分:1)
也许您可以尝试从下面的链接中另外设置代理,如下面的示例所示:-
https://www.tutorialspoint.com/apache_httpclient/apache_httpclient_proxy_authentication.htm
public class ProxyAuthenticationExample {
public static void main(String[] args) throws Exception {
//Creating the CredentialsProvider object
CredentialsProvider credsProvider = new BasicCredentialsProvider();
//Setting the credentials
credsProvider.setCredentials(new AuthScope("example.com", 80),
new UsernamePasswordCredentials("user", "mypass"));
credsProvider.setCredentials(new AuthScope("localhost", 8000),
new UsernamePasswordCredentials("abc", "passwd"));
//Creating the HttpClientBuilder
HttpClientBuilder clientbuilder = HttpClients.custom();
//Setting the credentials
clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider);
//Building the CloseableHttpClient object
CloseableHttpClient httpclient = clientbuilder.build();
//Create the target and proxy hosts
HttpHost targetHost = new HttpHost("example.com", 80, "http");
HttpHost proxyHost = new HttpHost("localhost", 8000, "http");
//Setting the proxy
RequestConfig.Builder reqconfigconbuilder= RequestConfig.custom();
reqconfigconbuilder = reqconfigconbuilder.setProxy(proxyHost);
RequestConfig config = reqconfigconbuilder.build();
//Create the HttpGet request object
HttpGet httpget = new HttpGet("/");
//Setting the config to the request
httpget.setConfig(config);
//Printing the status line
HttpResponse response = httpclient.execute(targetHost, httpget);
System.out.println(response.getStatusLine());
} }