如果我使用浏览器访问某个直接下载URL
,它会自动下载该文件。但是,当我使用 Java
代码下载文件时,我得到的是 HTML
代码而不是文件内容:
<html>
<body>
<script type="text/javascript" src="/aes.js"></script>
<script>function toNumbers(d) {
var e = [];
d.replace(/(..)/g, function (d) {
e.push(parseInt(d, 16))
});
return e
}
function toHex() {
for (var d = [], d = 1 == arguments.length && arguments[0].constructor == Array ? arguments[0] : arguments, e = "", f = 0; f < d.length; f++) e += (16 > d[f] ? "0" : "") + d[f].toString(16);
return e.toLowerCase()
}
var a = toNumbers("f655ba9d09a112d4968c63579db590b4"), b = toNumbers("98344c2eee86c3994890592585b49f80"),
c = toNumbers("b5eb8dc5c53e5107faa7ec1c1f3e3dc7");
document.cookie = "__test=" + toHex(slowAES.decrypt(c, 2, a, b)) + "; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/";
location.href = "http://example.com/Test.txt?i=1";</script>
<noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with
Javascript support
</noscript>
</body>
</html>
我的文件下载代码是例如以下内容:
URL url = new URL("...");
try (InputStream inputStream = url.openStream())
{
Files.copy(inputStream, downloadedFilePath, REPLACE_EXISTING);
}
如何在 Java
中以编程方式下载文件? There are ways to execute JavaScript
但它到底应该如何工作呢?似乎必须(正确)设置 document.cookie
才能下载。
最佳答案
通过在请求旁边传递正确的 cookie 值来进行下载。可以使用例如检索 cookie 值Google Chrome
DevTools
-> 应用程序
-> Cookies
。由于在我的示例中 cookie 值不会更改,因此类似以下的代码就可以解决问题:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadWithCookieExample
{
public static void main(String[] arguments)
{
try
{
URL url = new URL("...");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Cookie", "blabla"); // Hard-coded correct cookie value
String readStream = readStream(con.getInputStream());
System.out.println(readStream);
} catch (Exception exception)
{
exception.printStackTrace();
}
}
private static String readStream(InputStream inputStream) throws IOException
{
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)))
{
String line;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line);
stringBuilder.append(System.lineSeparator());
}
}
return stringBuilder.toString().trim();
}
}
更好的解决方案是执行 JavaScript
来接收 cookie 值并传递结果。对于知道如何优雅地完成此任务的人来说,此任务将作为另一个答案的练习。
关于javascript - 在 Java 中使用 JavaScript Cookie 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55881026/