gpt4 book ai didi

Android/Java : HttpURLConnection doesn't return headers of redirected file (e. g。在 S3)

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:22:15 28 4
gpt4 key购买 nike

我的代码(转载如下)连接到一个 url 并将文件下载到 android 上的磁盘。所有标准的东西。当我尝试在通过映射到存储桶的服务器上的子域访问的 S3 上的文件上使用此代码时(例如 foo.example.com => 称为 foo.example.com 的存储桶),它经常失败。结果(使用方便的 curl 命令..

 "curl -v -L -X GET http://foo.example.com/f/a.txt") 

.. 这里正在进行重定向。

文件下载工作正常,因为默认情况下 HttpURLConnection 会遵循重定向,但是需要 header 信息的调用(getContentLength、getHeaderFieldDate("Last-Modified", 0 ) 等)会从 307 重定向返回 header ,并且不是下载的实际文件。

有人知道如何解决这个问题吗?

谢谢

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);
}

最佳答案

您是否尝试过将重定向设置为 false 并尝试手动捕获重定向的 URL 和关联的 header 字段?

例如这样的事情:

URL url = new URL(url); 
HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
ucon.setInstanceFollowRedirects(false);
URL secondURL = new URL(ucon.getHeaderField("Location"));
URLConnection conn = secondURL.openConnection();

此示例捕获重定向的 URL,但您可以轻松调整它以尝试任何其他 header 字段。这有帮助吗?

关于Android/Java : HttpURLConnection doesn't return headers of redirected file (e. g。在 S3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5118947/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com