Tuesday, March 19, 2013

Android - passing WebView cookie to HttpURLConnection

Since I needed to use WebView and session was created in the server side by PHP when login by WebView, cookie is required to pass into the HttpURLconnection for getting the InputStream later, which I mentioned in my previous posts, download PDF in WebView.

The code finally is not too complicated, however, it used me up almost a whole day to figure out how it works.

Before downloading the PDF, get the cookie by CookieManger as below:

private class DownloadPDF extends AsyncTask<String, Integer, String> {

 @Override
        protected String doInBackground(String... sUrl) {  
            try {
                 CookieManager cookieManager = CookieManager.getInstance();
                 String cookie = cookieManager.getCookie(new URL(sUrl[0]).getHost());
                 //or String cookie = cookieManager.getCookie("www.example.com");

                URL url = new URL(sUrl[0]);
             
                File myDir = new File(Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_DOWNLOADS).toString()+"/myPDF");
             
                if (!myDir.exists()) myDir.mkdirs();          

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
             
                //Then, set cookie to the connection by setRequestProperty
                connection.setRequestProperty("Cookie",cookie);

                connection.setDoOutput(true);        

                connection.connect();
                ...
                //rest of code mentioned in previous post for downloading a PDF file which is generated by TCPDF on server side.
                ...
}

So, basically, only 3 lines of code and get this done!

No comments: