Thanks in advance..

First, I'm asking this for android.

I have to send a http post request with a zip file containing an xml file having list of names in it.

now, according to the list of name I sent, the server will send me the binary data of a zip file and I have to save that binary data (response) as a zip file.

the problem is, when I'm saving this binary data as a zip file, it is not able to extract the zip then.

I think this could be some character set problem too.. that i need to convert the received binary data to some character set and then save it as a zip..

please Help me in this, I'm new to android. and any ASYNC task example for doing the same will be great Help.

This is my code..

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)
{

}
}
有帮助吗?

解决方案

Readers are not meant to read octet streams.

Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

You're looking for a BufferedInputStream.

The getContent() method on the HttpEntity returns an InputStream. Wrap this around a BufferedInputStream and write it to a file or a 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();

To save on memory I'd advise you to write to a BufferedOutputStream instead of trying to get the bytes from the stream into a data structure. The android device is likely to run out of memory for large zip files.

其他提示

Maybe you can try this:

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)
{

}
}

If you covert the bytes to a String and then get bytes by String.getBytes() ,you need to assume that the encoding must be single-byte like iso-8859-1(not utf-8 nor others).

Change your code from BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

to

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

And then bObj.write(stringBuffer.toString().getBytes());

to

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top