2

I'm working on an android app that needs to save a pdf file from an api. So I had to extend Request volley class to a ByteArray class:

package br.com.tarcisojunior.myapp;

import android.support.annotation.NonNull;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;

/**
 * Created by tarcisojunior on 18/04/18.
 */

public class ByteArrayRequest extends Request<byte[]> {
    private final Response.Listener<byte[]> mListener;


    public ByteArrayRequest(String url, Response.Listener<byte[]> listener,
                       Response.ErrorListener errorListener) {
        this(Method.GET, url, listener, errorListener);
    }

    public ByteArrayRequest(int method, String url, Response.Listener<byte[]> listener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        mListener = listener;

    }


    @Override
    protected Response parseNetworkResponse(NetworkResponse response) {
        return Response.success(response.data, HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    protected void deliverResponse(byte[] response) {
        if(null != mListener){
            mListener.onResponse(response);
        }
    }

    @Override
    public String getBodyContentType() {
        return "application/octet-stream";
    }

}

I my Activity i'm calling ByteArrayRequest to perform an api request:

private void getCarnePDF(final int empreendimento,final int coligada,final String quadra,final String lote){ RequestQueue requestQueue; ByteArrayRequest request;

requestQueue = Volley.newRequestQueue(this);

request = new ByteArrayRequest(Request.Method.GET, getString(R.string.baseUrl) + getString(R.string.carnePdfUrl),
        new Response.Listener<byte[]>() {
            @Override
            public void onResponse(byte[] response) {
                Log.i("getBilletCard", response.toString());
                try {
                    byte[] bytes = response;
                    saveToFile(bytes, "card.pdf");
                }catch (Exception e){
                    Toast.makeText(BilletCardActivity.this, "Erro ao converter resposta", Toast.LENGTH_LONG).show();
                }
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }){

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> headers = new HashMap<String, String>();
        //headers.put("Content-Type", "application/json");
        headers.put("token", token);
        headers.put("empreendimento", String.valueOf(empreendimento));
        headers.put("coligada", String.valueOf(coligada));
        headers.put("quadra", quadra);
        headers.put("lote",lote);
        return headers;
    }
};

requestQueue.add(request);

}

and in listener the saveToFile function should create the pdf file. The pdf file is created but raises an error "Can't open file". Here's my saveToFile function:

public void saveToFile(byte[] byteArray, String pFileName){
        File f = new File(Environment.getExternalStorageDirectory() + "/myappname");
        if (!f.isDirectory()) {
            f.mkdir();
        }

        String fileName = Environment.getExternalStorageDirectory() + "/myappname/" + pFileName;

        try {

            FileOutputStream fPdf = new FileOutputStream(fileName);

            fPdf.write(byteArray);
            fPdf.flush();
            fPdf.close();
            Toast.makeText(this, "File successfully saved", Toast.LENGTH_LONG).show();
        } catch (FileNotFoundException e) {
            Toast.makeText(this, "File create error", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            Toast.makeText(this, "File write error", Toast.LENGTH_LONG).show();
        }

}

The file is successfully create, but it doesn't open file created

Can't open file When I tried same endpoint from Postman, everything works fine and file is successful saved and opened When I try from Postman, file is successfully saved and open flawless

Tarciso Junior
  • 549
  • 9
  • 16
  • Did you compare amount of bytes from original file and your copy? – greenapps Apr 18 '18 at 14:57
  • when i do a request to same endpoint from Postman, file is downloaded and save successfully, when i locate the file in Finder, file size is 123 K, but as we can see in first image, android saved file size is 120Kb. Question edited to add response headers from Postman – Tarciso Junior Apr 18 '18 at 15:16

1 Answers1

2

after comparing Postman headers with my code, I've found that a "Cache-control=no-cache" header was missing in request.

After add this header, file was correctly downloaded.

so changed to this: . . . . .

 @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Cache-Control", "no-cache");
        headers.put("token", token);
        headers.put("empreendimento", String.valueOf(empreendimento));
        headers.put("coligada", String.valueOf(coligada));
        headers.put("quadra", quadra);
        headers.put("lote",lote);
        return headers;
    }

. . . . .

Tarciso Junior
  • 549
  • 9
  • 16