Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Get pdf file as a result of httppost

I'm developping an Android application which must download some files from a web service.

Goal

I want download a PDF file from a web service and show it on the phone.

Problem

I'm newbie working with webservices and I'dont have so clear how to get the file and open it.

Here it's my code to date:

public void downloadFile(String username, String password, String filename) {       
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("username", username));
    nameValuePairs.add(new BasicNameValuePair("password", password));
    nameValuePairs.add(new BasicNameValuePair("filename", filename));

    String output = httpPost(URL_DESCARGAS, nameValuePairs);
}

private String httpPost(String url, List<NameValuePair> nameValuePairs) {
    /* Create new HttpClient and Post Header */
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

    try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

        /* Get output */            
        return inputStreamToString(response.getEntity().getContent()).toString();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}

I don't have to return String of response, but I don't know what I have to do. So how to show pdf that returns web service?

In another activity I have to execute the same but web service returns a .png and I want to show that in an imageview or something like that. It is done in the same way?

Thank you very much. I've searched for a long time but I didn't found anything.

Edit

I've found that url: http://www.androidsnippets.com/download-an-http-file-to-sdcard-with-progress-notification and I use what it says, but file is not created (I don't see it in sdcard root).

Here is my modified code:

public void downloadFile(String username, String password, String filename) {       
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("username", username));
    nameValuePairs.add(new BasicNameValuePair("password", password));
    nameValuePairs.add(new BasicNameValuePair("filename", filename));

    HttpResponse response = httpPost(URL_DESCARGAS, nameValuePairs);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        try {
            InputStream inputStream = entity.getContent();
             //set the path where we want to save the file
            //in this case, going to save it on the root directory of the
            //sd card.
            File SDCardRoot = Environment.getExternalStorageDirectory();
            //create a new file, specifying the path, and the filename
            //which we want to save the file as.
            File file = new File(SDCardRoot, filename);

            //this will be used to write the downloaded data into the file we created
            FileOutputStream fileOutput = new FileOutputStream(file);

            //create a buffer...
            byte[] buffer = new byte[1024];
            int bufferLength = 0; //used to store a temporary size of the buffer

            //now, read through the input buffer and write the contents to the file
            while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                //add the data in the buffer to the file in the file output stream (the file on the sd card
                fileOutput.write(buffer, 0, bufferLength);
            }
            //close the output stream when done
            fileOutput.close();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Can you help me? I need to create that file and show it in the phone at the moment.

like image 552
Lyd Avatar asked Oct 21 '22 06:10

Lyd


1 Answers

I've solved that. I forgot to put permissions in AndroidManifest.xml.

Here is my code that gets output of httppost, creates file in SD card and opens it in the pdf viewer that user has installed in device:

Activity class

public void downloadInvoice(View view) {
    boolean ok = myApplication.downloadFile("pdf");
    if (!ok) {
        //If not ok, show error message
    } else {
        //Open file in pdf viewer that user has in the device
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() 
                +"/"+ myApplication.getActualUser().getActualInvoice().getPdf());
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file));
        intent.setType("application/pdf");
        startActivity(intent);
    }
}

AndroidManifest.xml

...
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
like image 146
Lyd Avatar answered Oct 24 '22 04:10

Lyd