从httppost响应中下载并保存zip文件作为ANDROID中的二进制数据

时间:2014-04-10 05:53:26

标签: java android android-asynctask zip binary-data

提前致谢..

首先,我问这个问题。

我必须发送一个带有zip文件的http post请求,该文件包含一个包含名称列表的xml文件。

现在,根据我发送的名称列表,服务器将向我发送一个zip文件的二进制数据,我必须将该二进制数据(响应)保存为zip文件。

问题是,当我将这个二进制数据保存为zip文件时,它无法解压缩。

我认为这也可能是一些字符集问题..我需要将收到的二进制数据转换为某个字符集,然后将其保存为zip ..

请帮帮我,我是android的新手。并且任何ASYNC任务示例都可以提供相同的帮助。

这是我的代码..

private class sendMissingImagesToServer extends
        AsyncTask<String, Integer, byte[]> {

    @Override
    protected byte[] doInBackground(String... params) {
        String uri = params[0];
        try {

            MultipartEntityBuilder entity;
            File f;
            FileBody fb;
            entity = MultipartEntityBuilder.create();

            entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            f = new File(zipImageFile);
            fb = new FileBody(f);
            entity.addPart("orderFile", fb);
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(uri);
            Log.e("Uploload Missing Image URL", "" + uri);
            httppost.setEntity(entity.build());
            HttpResponse response = httpclient.execute(httppost);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer stringBuffer = new StringBuffer();
//              byte[] fileBites=null;
            String line = "";

            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
            bufferedReader.close();

//              fileBites=stringBuffer.toString().getBytes();
//              Log.e("FILE BITES", fileBites+"=>"+fileBites.length);

            ByteArrayOutputStream bObj = new ByteArrayOutputStream();
            bObj.reset();
            bObj.write(stringBuffer.toString().getBytes());

            return bObj.toByteArray();

//              return stringBuffer.toString();
        } catch (Exception e) {
            return e.toString().getBytes();
        }

    }

    @Override
    protected void onPostExecute(byte[] result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        Log.e("Response From Server", "" + result);
        writeToFile(result);

    }

}

@SuppressWarnings("resource")
private void writeToFile(byte[] data) {
    try {

        FileOutputStream fop = null;
        File file;

        file = new File(AppConstants.DataPath+"/products.zip");
        fop = new FileOutputStream(file);

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }
        try {            
        fop.write(data);

    } catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }
    unzipImage(AppConstants.DataPath + "/products.zip",
            AppConstants.DataPath);
}catch (Exception E)
{

}
}

2 个答案:

答案 0 :(得分:2)

也许你可以试试这个:

private class sendMissingImagesToServer extends
        AsyncTask<String, Integer, byte[]> {

    @Override
    protected byte[] doInBackground(String... params) {
        String uri = params[0];
        byte[] data;
        try {

            MultipartEntityBuilder entity;
            File f;
            FileBody fb;
            entity = MultipartEntityBuilder.create();

            entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            f = new File(zipImageFile);
            fb = new FileBody(f);
            entity.addPart("orderFile", fb);
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(uri);
            Log.e("Uploload Missing Image URL", "" + uri);
            httppost.setEntity(entity.build());
            HttpResponse response = httpclient.execute(httppost);
            InputStream input = response.getEntity().getContent();
            data = new byte[input.available()];
            input.read(data);
            return data;
        } catch (Exception e) {
            return e.toString().getBytes();
        }

    }

    @Override
    protected void onPostExecute(byte[] result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        Log.e("Response From Server", "" + result);
        writeToFile(result);

    }

}

@SuppressWarnings("resource")
private void writeToFile(byte[] data) {
    try {

        FileOutputStream fop = null;
        File file;

        file = new File(AppConstants.DataPath+"/products.zip");
        fop = new FileOutputStream(file);

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }
        try {            
        fop.write(data);

    } catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }
    unzipImage(AppConstants.DataPath + "/products.zip",
            AppConstants.DataPath);
}catch (Exception E)
{

}
}

如果将字节转换为String然后按String.getBytes()获取字节,则需要假设编码必须是单字节,如iso-8859-1(不是utf-8也不是其他)。

更改您的代码 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"ISO-8859-1"));

然后bObj.write(stringBuffer.toString().getBytes());

bObj.write(stringBuffer.toString().getBytes("ISO-8859-1"));

答案 1 :(得分:2)

读者并不打算阅读八位字节流。

  

从字符输入流中读取文本,缓冲字符,以便有效地读取字符,数组和行。

您正在寻找BufferedInputStream

getContent()上的HttpEntity方法返回InputStream。将其包裹在BufferedInputStream左右,并将其写入文件或ByteArrayOutputStream

        byte[] buffer = new byte[5 * 1024];
        int numRead = -1;
        while( (numRead = bufferedInputStream.read(buffer))!= -1)
        {
            byteArrayOutputStream.write(buffer, 0, numRead);
        }
        byteArrayOutputStream.flush();
        byteArrayOutputStream.close();
        byte[] result = byteArrayOutputStream.toByteArray();

为了节省内存,我建议你写一个BufferedOutputStream而不是试图将流中的字节转换成数据结构。对于大型zip文件,android设备可能会耗尽内存。