拥有 8,000 多个可下载 PDF 文件的 HTTP 链接列表。读取每个链接并调用我的方法 downloadFile() 并将其保存到本地 Window$ PC。遇到两种链接格式:
第一种类型(直接)始终有效。第二个不起作用。当它将文件另存为 pdf 时,它看起来像:
<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>
当我点击浏览器开发人员工具中的非工作链接时,它会被 JavaScript 文件重定向到 HTTPS 站点(将协议(protocol)更改为 HTTPS)。
我错过了什么?
我尝试设置 cookiehandler、将系统属性 http.strictPostRedirect 设置为 true、将连接 setFollowRedirects 和 setInstanceFollowRedirects 设置为 true、在转发/移动时创建新的 URL 连接、设置连接 setReadTimeout、为 SSL 创建 HttpsURLConnection。所有这些都不适用于 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 ) {
// Get new URL (https) from 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);
is = sc.getInputStream();
} else {
c.setFollowRedirects(true);
c.setInstanceFollowRedirects(true);
responseCode = c.getResponseCode();
is = 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( is != null ) {
is.close();
}
}
我是 servlet 的使用者,并且只有链接作为访问权限。 提前致谢!
最佳答案
无论您编写多少额外代码来执行 Java 默认情况下重定向时已经执行的操作,这永远都不会起作用。
HTML 页面会自动发布一个表单,该表单在浏览器加载时会导致下载。 Java 代码永远不会执行它。
关于java - 从 Servlet 下载文件的 HttpURLConnection 不起作用,直接链接有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29088387/