[英]Error while downloading the zip file from server to device?
我正在使用此代碼從服務器下載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 HttpComponents和Commons IO 。
httpConn.setDoOutput(false);
httpConn.setRequestProperty("Content-Type", "application/octet-stream");
httpConn.setRequestProperty("Content-Length", String.valueOf(file.length());
while (... > 0) {
fos.write(buffer, 0, len1);
fos.close();
僅寫入緩沖區中已填充的字節,即僅len1個字節。 它將解決您的問題,就好像緩沖區沒有完全填充一樣,我們將僅寫入那些讀取的字節。
while ( (len1 = in.read(buffer) )!=-1 ) {
fos.write(subArray(buffer,len1));
}
//Method to create su-array
public byte[] subArray(byte[] arr, int length) {
byte temp[] = new byte[length];
for (int i = 0; i < length; i++) {
temp[i] = arr[i];
}
return temp;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.