Android download pdf from URL -
i trying download pdf url pdf part of response stream rather attaching part of response. below code tried there not much luck because when pdf gets corrupted because there html content written inside. not sure problem is.
url url = new url(fileurl); httpurlconnection httpconn = (httpurlconnection) url.openconnection(); int responsecode = httpconn.getresponsecode(); // check http response code first system.out.println("resp: "+responsecode); if (responsecode == httpurlconnection.http_ok) { string filename = ""; string disposition = httpconn.getheaderfield("content-disposition"); string contenttype = httpconn.getcontenttype(); int contentlength = httpconn.getcontentlength(); if (disposition != null) { // extracts file name header field int index = disposition.indexof("filename="); if (index > 0) { filename = disposition.substring(index + 10, disposition.length() - 1); } } else { // extracts file name url filename = fileurl.substring(fileurl.lastindexof("/") + 1, fileurl.length()); } system.out.println("content-type = " + contenttype); system.out.println("content-disposition = " + disposition); system.out.println("content-length = " + contentlength); system.out.println("filename = " + filename); // opens input stream http connection inputstream inputstream = httpconn.getinputstream(); string savefilepath = savedir + file.separator + filename; // opens output stream save file fileoutputstream outputstream = new fileoutputstream(savefilepath); int bytesread = -1; byte[] buffer = new byte[1024*1024]; while ((bytesread = inputstream.read(buffer)) != -1) { outputstream.write(buffer, 0, bytesread); } outputstream.close(); inputstream.close(); system.out.println("file downloaded"); } else { system.out.println("no file download. server replied http code: " + responsecode); } httpconn.disconnect(); any help appreciated. give thanks you.
i utilize apache's commons-io fileutils.copyurltofile(url, java.io.file) accomplish task.
an illustration implementation be:
file f = new file(environment.getexternalstoragedirectory(), "foo.pdf"); url url = new url("https://foosite.com/files/foo.pdf"); fileutils.copyurltofile(new url("http://foo"), f); at point, file object ready processing.
reference: http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/fileutils.html
android pdf httprequest httpresponse android-download-manager
No comments:
Post a Comment