1

I am downloading and saving PDF file in android using this code :

HttpClient httpclient = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        HttpResponse response;
        FileOutputStream fileOutputStream;

         /*We will write the file to external storage.
            If External Storage is not available, then we use internal storage
          */
        ApplicationLevel appLevel=(ApplicationLevel) context;
        if(appLevel.isExternalStorageReadable() && appLevel.isExternalStorageWritable())
            file=new File(context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS),"example.pdf");
        else
            file=new File(context.getFilesDir(),"example.pdf");


        String path;
        android.util.Log.v(TAG,"strings[0] : "+strings[0]);
        try {
            URI uri = new URI("www.getpdf.com");
            request.setURI(uri);
            response = httpclient.execute(request);
            InputStream in = response.getEntity().getContent();
            String inputLine;

            fileOutputStream = new FileOutputStream(file);
            byte[] buf = new byte[1024];

            android.util.Log.v(TAG, "starting content reading..." );
            while ((in.read(buf)) > -1) {
                fileOutputStream.write(buf);
            }
            android.util.Log.v(TAG,"Content Reading done.");
            in.close();
            fileOutputStream.close();
        } catch (URISyntaxException e) {
            android.util.Log.v(TAG, e.toString());
            return false;
        } catch (IOException e) {
            android.util.Log.v(TAG, e.toString());
            return false;
        }


The downloaded pdf is not proper I think. When I try to open the pdf through "AdobeAcrobat" on my phone, it works sometimes and sometimes it is not able to render the pdf.
Am I downloading the pdf correctly?
This is the header of php which is returning the PDF

 header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
               header("Cache-Control: public");
               header("Content-Type: application/pdf");
               header("Content-Transfer-Encoding: Binary");
               header("Content-Length:".filesize($attachment_location));
               header("Content-Disposition: inline; filename=$_GET[get].pdf");
Ashwin
  • 12,691
  • 31
  • 118
  • 190
  • 1
    Refer this http://stackoverflow.com/questions/24740228/android-download-pdf-from-url-then-open-it-with-a-pdf-reader – sasikumar Jun 25 '15 at 07:01
  • Refer this http://stackoverflow.com/questions/9551058/urlconnection-or-httpclient-which-offers-better-functionality-and-more-efficie HttpURLConnection is the best choice. Its simple API and small size makes it great fit for Android. Transparent compression and response caching reduce network use, improve speed and save battery. – Srishti Roy Jun 25 '15 at 07:11

1 Answers1

2

I would change the while loop this way

 int read = 0;
 while ((read = in.read(buf)) > -1) {
      fileOutputStream.write(buf, 0, read);
 }

you can't be sure to read exactly 1024 bytes, your buffer size, at every iteration, and I would add a finally clause for closing the streams:

try {

} catch(..) {

} finally {
  // here call fileOutputStream.close()
  // and in.close()
}

finally is always called, even in case of exception. So you will not leak the stream in case of error

I would recommend you to stop using the Http apache client, and start using HttpUrlConnection instead.

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
  • what is the variable buf you are referring to? – Ashwin Jun 25 '15 at 07:14
  • `byte[] buf = new byte[1024];` ? – Blackbelt Jun 25 '15 at 07:15
  • the most apt answer man. This was the problem all along. I think it was adding some junk value since I was forcing 1024 bytes to be written everytime. Thanks for the answer! A very subtle solution. Can you also tell why you prefer HttpURLConnection over HttpClient? – Ashwin Jun 25 '15 at 07:33
  • HttpClient is deprecated, and it will be probably be removed with Android M. – Blackbelt Jun 25 '15 at 07:34
  • Okay, but we can always incorporate the apache library again right? – Ashwin Jun 25 '15 at 07:35
  • 1
    cool. Anywa, thanks for the answer! Great answer I believe which goes to the fundamental level – Ashwin Jun 25 '15 at 07:37