首页 > 解决方案 > Java Apache HTTP 401 响应返回正确的凭据

问题描述

我正在尝试使用 Apache HttpClient 访问 REST API 链接,但一直返回 401 错误。在提示输入密码后,当我在浏览器中转到 URL 时,我可以登录。我正在使用的代码如下:

        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(creds.get(0), creds.get(1));
        provider.setCredentials(AuthScope.ANY, credentials);

        AuthCache authCache = new BasicAuthCache();
        authCache.put(new HttpHost(uri.getHost(), uri.getPort(), "https"), new BasicScheme());

        BasicHttpContext context = new BasicHttpContext();
        context.setAttribute(ClientContext.CREDS_PROVIDER, provider);
        context.setAttribute(ClientContext.AUTH_CACHE, authCache);

        DefaultHttpClient client = new DefaultHttpClient();
        client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler());
        client.setCredentialsProvider(provider);
        HttpResponse response = null;
        try
        {
            // response = client.execute(new HttpGet(uri));
            response = client.execute(new HttpGet(uri), context);
        }
        catch(IOException e)
        {
            logger.error("Error running authenticated get request: " + e);
        }

我正在使用 HttpClient 4.2.3,不幸的是我无法升级它。

任何帮助,将不胜感激!谢谢!

编辑:原来我需要提供证书,比如在 curl 中使用 -cacert,但是我找不到这样的例子!

标签: javaapache-httpclient-4.x

解决方案


由于您需要提供证书,因此这可能会有所帮助:

http://hc.apache.org/httpcomponents-client-4.2.x/httpclient/examples/org/apache/http/examples/client/ClientCustomSSL.java

我认为该示例符合 4.2.3 。


推荐阅读