java - 将 zip 文件从服务器下载到设备时出错?

标签 java android zip

我正在使用此代码从服务器下载 zip 文件

private static InputStream OpenHttpConnection(String urlString) 
        throws IOException
        {
            InputStream in = null;
            int response = -1;

            URL url = new URL(urlString); 
            URLConnection conn = url.openConnection();

            if (!(conn instanceof HttpURLConnection))                     
                throw new IOException("Not an HTTP connection");

            try{
                System.out.println("OpenHttpConnection called");

                HttpURLConnection httpConn = (HttpURLConnection) conn;
                httpConn.setAllowUserInteraction(false);
                httpConn.setInstanceFollowRedirects(true);
                httpConn.setRequestMethod("GET");
                httpConn.setDoOutput(true);
                httpConn.setDoInput(true);
                httpConn.setRequestProperty("content-type", "binary/data");

                httpConn.connect(); 

                response = httpConn.getResponseCode();

                System.out.println("response is"+response);
                System.out.println(HttpURLConnection.HTTP_OK);

                if (response == HttpURLConnection.HTTP_OK) {
                    in = httpConn.getInputStream();
                    System.out.println("Connection Ok");
                    return in;
                    }                     
            }
            catch (Exception ex)
            {
                throw new IOException("Error connecting");            
            }
            return in;     
        }

                 private static void saveToInternalSorage(InputStream in,String filename,Context ctx){



//fos =openFileOutput(filename, Context.MODE_WORLD_READABLE);

try {
  //  System.out.println("mypath = "+mypath);
    //fos = new FileOutputStream(mypath);
    FileOutputStream fos = (ctx).openFileOutput(filename, Context.MODE_WORLD_READABLE);

    byte[] buffer=new byte[1024];






    int len1 ;
    while ( (len1 = in.read(buffer) )!=-1 ) {
        fos.write(buffer);


    }

    // Use the compress method on the BitMap object to write image to the OutputStream


} catch (Exception e) {
    e.printStackTrace();
}
}

下载的zip文件已损坏,文件的实际大小为3.5kb,但下载的文件为5kb。代码有什么问题请帮忙?

最佳答案

这个

while ( (len1 = in.read(buffer) )!=-1 ) {
        fos.write(buffer);


    }

您将在每次迭代中写入整个缓冲区(1024 字节)。您应该只写入 len1 字节(读取的字节数)。

顺便说一句,您可能希望考虑使用一些更高级别的抽象库来处理 HTTP 和流操作等内容。 Apache Commons HttpComponentsCommons IO例如。

关于java - 将 zip 文件从服务器下载到设备时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9533550/

相关文章:

java - 在 jsch ChannelExec 上设置环境变量

java - Android - 使用自定义按钮的自定义 View 使整个屏幕都可以点击,而不仅仅是在按钮区域

java - Android 使用单一方法对不同表进行 CRUD 操作

php - 如何使用 PHP 创建 ZIP 文件并在用户下载后将其删除?

java - 使用 Java 将多个 pdf 压缩为单个 zip 文件

java - 在 Netty 中禁用 HTTP 协议(protocol)请求?

java - 如何确保 4 个随机变量永远不相等?

安卓 SQLite 示例

maven - 使用 Maven 解压 zip 中的内部 zip

java - 复合对象中的父子关系?