java - 使用 Apache HTTP 组件的 HTTP 身份验证 : force sending of challenge

标签 java http-authentication apache-httpcomponents

我需要与需要身份验证的模糊网络服务器通信。如果我不提供凭据,则会显示登录表单。但是,如果我提供未经请求的基本身份验证凭据,我将直接访问所需的内容。

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 程序发送凭据?

最佳答案

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

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;,但反过来我们可以删除与凭证相关的导入。)

关于java - 使用 Apache HTTP 组件的 HTTP 身份验证 : force sending of challenge,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9805155/

相关文章:

java - Admob 广告无法根据屏幕方向正确调整大小 [包括图片]

java - Android 在网络不可用时将 http 请求排队并在打开时处理它们

ios - 如何检测来自 UIWebView 的身份验证质询?

java - 在检索重定向 url 之前使用 Apache HttpHead 进行 URI 编码

java-apache http 客户端查询,涉及作为多部分发布请求的一部分提交文件

java - 多线程(多请求)调用的Spring @Transactional方法

security - HTTP 认证安全

php - 结合 HTTP 身份验证和 PHP session ?

java - 在 Mockito 中使用 ResponseHandler 模拟 Apache HTTPClient

java - 大(该死的)二进制矩阵的优化