通过HttpConnection下载大文件

编程入门 行业动态 更新时间:2024-10-22 16:34:53
本文介绍了通过HttpConnection下载大文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用以下代码我可以从url加载任何文件作为字节,但这种方式适用于不大于256kb的文件。

Using the following code i can load any file from url as a bytes but this way works fine for file not larger than 256kb .

所以我想用另一种方法将较大的文件作为字节加载而不使用 BlackBerry Combiner

So I want another way to load larger files as bytes without using BlackBerry Combiner

我的代码:

HttpConnection hpc = null; try { hpc = (HttpConnection) Connector.open(url + ConnectionManager.getTimeOut(5000) + ConnectionManager.updateConnectionSuffix()); hpc.setRequestMethod(HttpConnection.GET); hpc.setRequestProperty("Connection", "Keep-Alive"); if (hpc.getResponseCode() != 200) { return null; } byte[] data = IOUtilities.streamToBytes(hpc.openInputStream()); hpc.close(); return data; } catch (Exception e) { return null; }

推荐答案

我试图调整 BlackBerry组合器 使用它下载大文件作为字节。它适用于我下面列出的代码

i tried to adjust BlackBerry Combiner to use it on download large File as Bytes . and it works fine for me the code listed below

---调用

byte[] data = downloadLargeFiles(url); if (data != null) { invoke(data.length + " "); Bitmap bitmap = Bitmap.createBitmapFromBytes(data, 0, data.length, 1); manager.add(new BitmapField(bitmap)); }

---函数

public byte[] downloadLargeFiles(String url) throws Exception { int chunkIndex = 0; int totalSize = 0; String currentFile = url + ConnectionManager.getTimeOut(5000) + ConnectionManager.updateConnectionSuffix(); HttpConnection conn; InputStream in; int rangeStart = 0; int rangeEnd = 0; int chunksize = 100000; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while (true) { conn = (HttpConnection) Connector.open(currentFile, Connector.READ_WRITE, true); rangeStart = chunkIndex * chunksize; rangeEnd = rangeStart + chunksize - 1; conn.setRequestProperty("Range", "bytes=" + rangeStart + "-" + rangeEnd); int responseCode = conn.getResponseCode(); if (responseCode != 200 && responseCode != 206) { // Dialog.alert("End "+responseCode); break; } in = conn.openInputStream(); int length = -1; byte[] readBlock = new byte[256]; int fileSize = 0; while ((length = in.read(readBlock)) != -1) { bos.write(readBlock, 0, length); fileSize += length; Thread.yield(); // Try not to get cut off } totalSize += fileSize; chunkIndex++; // index (range) increase in.close(); conn.close(); in = null; conn = null; Thread.sleep(1000); } bos.close(); return bos.toByteArray(); }

谢谢

更多推荐

通过HttpConnection下载大文件

本文发布于:2023-11-25 17:39:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630714.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:大文件   HttpConnection

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!