我的代码(转载如下),连接到一个url并将文件下载到android上的磁盘.所有标准的东西.当我尝试在通过映射到存储桶的服务器上的子域(例如foo.example.com =>存储桶名为foo.example.com)访问的S3上的文件上使用此代码时,它通常会失败.结果(使用方便的卷曲命令..
"curl -v -L -X GET http://foo.example.com/f/a.txt")
..这里有一个重定向.
文件下载工作正常,因为默认情况下HttpURLConnection将遵循重定向,但需要标头信息的调用(getContentLength,getHeaderFieldDate("Last-Modified",0)等)将返回307重定向的标头,而不是实际的文件已下载.
有谁知道怎么解决这个问题?
谢谢
File local = null;
try {
Log.i(TAG, "Downloading file " + source);
conn = (HttpURLConnection) new URL(source).openConnection();
fileSize = conn.getContentLength(); // ** THIS IS WRONG ON REDIRECTED FILES
out = new BufferedOutputStream(new FileOutputStream(destination, false), 8 * 1024);
conn.connect();
stream = new BufferedInputStream(conn.getInputStream(), 8 * 1024);
byte[] buffer = new byte[MAX_BUFFER_SIZE];
while (true) {
int read = stream.read(buffer);
if (read == -1) {
break;
}
// writing to buffer
out.write(buffer, 0, read);
downloaded += read;
publishProgress(downloaded, fileSize);
if (isCancelled()) {
return "The user cancelled the download";
}
}
} catch (Exception e) {
String msg = "Failed to download file " + source + ". " + e.getMessage();
Log.e(TAG, msg );
return msg;
} finally {
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
Log.e(TAG, "Failed to close file " + destination);
e.printStackTrace();
}
}
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
Log.e(TAG, "Failed to close file " + destination);
e.printStackTrace();
}
} else {
long dateLong = conn.getHeaderFieldDate("Last-Modified", 0 ); // ** THIS IS WRONG ON REDIRECTED FILES
Date d = new Date(dateLong);
local.setLastModified(dateLong);
}