【发布时间】:2011-09-09 03:45:05
【问题描述】:
我正在寻求有关如何将图像文件从受密码保护的文件夹下载到我的 Android 应用程序的帮助。我拥有的代码使用 URLConnection 和 getInputStream/BufferedInputStream 但我看不到如何在其中获取用户名/密码身份验证。我看到 HttpClient 有 UsernamePasswordCredentials - 但我不知道如何使用 HttpClient 下载文件,所以这对我没有多大帮助。
这是我目前找到的代码,如何使用它下载文件?
public class ClientAuthentication {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 443),
new UsernamePasswordCredentials("username", "password"));
HttpGet httpget = new HttpGet("https://localhost/protected");
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
或者,我有这个用于下载文件的代码——我将如何向它添加凭据:
http://www.helloandroid.com/tutorials/how-download-fileimage-url-your-device
谢谢!
编辑:好吧,在这里没有得到太多帮助。我找到了这个答案,我将尝试为我的目的返工:Download a file with DefaultHTTPClient and preemptive authentication
【问题讨论】:
-
你有没有试过把它放到像
https://user:password@host.domain/page/这样的URL中? -
是的,我做到了,它给了我文件 io 异常。不过,这在 iOS 中有效!
-
好问题,我开始认为这实际上是一个文件 i/o 问题——我可能对我使用的代码示例太信任了!但我更喜欢使用 HttpClient 身份验证代码而不是内联身份验证,所以我看看我是否可以让它工作。
标签: android authentication download