【问题标题】:HTTP authentication with Apache HTTP Components: force sending of challenge使用 Apache HTTP 组件进行 HTTP 身份验证:强制发送质询
【发布时间】:2012-03-21 13:00:32
【问题描述】:

我需要与需要身份验证的不起眼的网络服务器交谈。如果我不提供凭据,则会显示一个登录表单。但是,如果我确实提供了未经请求的基本身份验证凭据,我会直接获得所需的内容。

wget 直接支持这个:

# this fails and downloads a form:
wget https://weird.egg/data.txt --http-user=me --http-password=shhh

# this works and downloads the document:
wget https://weird.egg/data.txt --http-user=me --http-password=shhh --auth-no-challenge

现在我的问题是:如何使用 Apache 的 HTTP 组件在 Java 中进行下载?

这是我到目前为止所得到的。 (还有一个代理,我在wget 中使用-Y on,并且我有一个匹配的https_proxy 环境变量。)

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import java.net.URI;

// ...

DefaultHttpClient hc = new DefaultHttpClient();
hc.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxy_name, proxy_port));

URI uri = new URI("https://weird.egg/data.txt");

hc..getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME), new UsernamePasswordCredentials("me", "shh"));

hc.execute(new HttpGet(uri)); // etc

但是,我最终只得到了登录表单页面,而不是实际的文档。我怀疑 DefaultHttpClient 没有像wget 那样主动发送凭据。有没有办法让 Java 程序发送凭据?

【问题讨论】:

    标签: java http-authentication apache-httpcomponents


    【解决方案1】:

    没关系。我通过不尝试使用任何库身份验证方法解决了这个问题,而只是将基本身份验证标头强制强制到请求中:

    HttpGet get = new HttpGet(uri);
    
    String basic_auth = new String(Base64.encodeBase64((username + ":" + password).getBytes()));
    get.addHeader("Authorization", "Basic " + basic_auth);
    
    hc.execute(get); // etc
    

    (这需要额外的import org.apache.commons.codec.binary.Base64;,但反过来我们可以删除与凭据相关的导入。)

    【讨论】:

    • 好主意,谢谢。框架解决方案也不适合我。手动添加标题有效。
    • 谢谢。我在使用 Maven HTTP Wagon 客户端时遇到了同样的问题,并通过手动添加 Header 来解决它。
    • 现在你可以使用java.util.Base64.getEncoder().encodeToString(something),不需要依赖import org.apache.commons.codec.binary.Base64;
    猜你喜欢
    • 1970-01-01
    • 2010-12-03
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多