Android / Java:HttpURLConnection不返回重定向文件的标头(例如在S3上)

前端之家收集整理的这篇文章主要介绍了Android / Java:HttpURLConnection不返回重定向文件的标头(例如在S3上)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的代码(转载如下),连接到一个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,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及其关联的标头字段?

例如这样的事情:

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,但您可以轻松调整此项以尝试任何其他标头字段.这有帮助吗?

原文链接:https://www.f2er.com/android/316328.html

猜你在找的Android相关文章