【发布时间】:2011-05-12 13:56:02
【问题描述】:
在我的浏览器或 iOS 中,当我尝试获取带有编码的 http 身份验证信息的 URL 内容时
http://myUser:myPassword@www.example.com/secure/area/index.html
它只是工作。我正在从 Web 服务获取 URL,如果我能提供帮助,我想避免尝试解析它们以获取其 HTTP 身份验证信息。有没有办法在 Android 中做类似的事情而不实际解析 URL?或者,最好的方法是什么?
更新: 我发现当我尝试在 Authorization 标头中设置身份验证信息时,我得到一个非常奇怪的 FileNotFoundException。
这是我正在使用的代码:
URL url = new URL(urlString);
URLConnection connection;
String authority = url.getAuthority();
if (authority.contains("@")) {
String userPasswordString = authority.split("@")[0];
url = new URL(urlString.replace(userPasswordString + "@", ""));
connection = url.openConnection();
String encoded = new String(Base64.encode(userPasswordString.getBytes(), Base64.DEFAULT), "UTF-8");
connection.setRequestProperty("Authorization", "Basic " + encoded);
} else {
connection = url.openConnection();
}
InputStream responseStream = connection.getInputStream();
所有信息似乎都检查过了,我已经验证了 url 是正确的,base64 字符串是正确的,并且文件肯定在服务器上——我用 Firefox 打开它完全没有问题,并且 Firebug 显示据我所知,所有正确的标题都与我发送的内容相匹配。我得到的是以下错误(更改了 url 主机以保护无辜者):
java.io.FileNotFoundException: http://a1b.example.com/grid/uploads/profile/avatar/user1/custom-avatar.jpg
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
知道这是怎么回事吗?
我研究过使用 HttpClient,但在 Issue 16041 中看到建议我们更喜欢 URLConnection。
【问题讨论】:
标签: android httpurlconnection http-authentication