gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:28:52 24 4
gpt4 key购买 nike

我正在使用此代码从服务器下载 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/

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