java - HttpURLConnection to download file from Servlet not working, direct link works -
have list of 8,000+ http links pdf files download. reading in each link , calling method downloadfile() , saving local window$ pc. coming across 2 link formats:
the first type (direct) works. second 1 not work. when saves file pdf, looks like:
<div id="error"> <ul> </ul> </div> <form id="download" name="download" method="post" action="/caremanager/downloadformcontroller.do?attachmentid=2000"> <input type="hidden" name="attachid" value="2000" > </form> <script language="javascript" type="text/javascript"> document.forms[0].submit(); </script> </body> </div>
when follow non-working links in browser's developer tools, getting redirected https site (changing protocol https) javascript files.
what missing?
i have tried setting cookiehandler, setting system property http.strictpostredirect true, setting connections setfollowredirects , setinstancefollowredirects true, creating new url connection if forwarded/moved, setting connection setreadtimeout, creating httpsurlconnection ssl. have not worked servlet.
public static void downloadfile(string downloadurl, string filename) throws exception { cookiehandler.setdefault( new cookiemanager( null, cookiepolicy.accept_all ) ); // string cookie = cookiemanager.getinstance().getcookie( downloadurl.tostring() ); url url = new url( downloadurl ); file file = new file( "c:\\temp\\smc1\\" + filename ); httpurlconnection c = (httpurlconnection) url.openconnection(); system.setproperty("http.strictpostredirect", "true"); int responsecode = c.getresponsecode(); inputstream is; if( responsecode == httpurlconnection.http_moved_perm || responsecode == httpurlconnection.http_moved_temp || responsecode == httpurlconnection.http_see_other ) { // new url (https) httpurlconnection frowarding url newurl = new url( c.getheaderfield("location") ); httpurlconnection sc = (httpurlconnection) newurl.openconnection(); sc.setfollowredirects(true); sc.setinstancefollowredirects(true); responsecode = sc.getresponsecode(); // sc.setreadtimeout(15*1000); = sc.getinputstream(); } else { c.setfollowredirects(true); c.setinstancefollowredirects(true); responsecode = c.getresponsecode(); = c.getinputstream(); } // system.out.println( " code: " + responsecode ); fileoutputstream fos = new fileoutputstream( file ); int bytesread; byte[] buffer = new byte[ 1024 ]; while( ( bytesread = is.read(buffer) ) != -1 ) { fos.write(buffer, 0, bytesread); } if( fos != null ) { fos.flush(); fos.close(); } if( != null ) { is.close(); } }
i consumer of servlet , have link access. ahead of time!
this never work, no matter how code write java default when redirecting.
the html page auto-posts form causes download when loaded browser. java code never execute that.
Comments
Post a Comment