我的代码(转载如下),连接到一个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重定向的标头,而不是实际的文件已下载.@H_301_5@
谢谢@H_301_5@
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,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); }