JAVA:如何从需要启用 cookie 的站点下载 HTML 文件?

标签 java html cookies

我正在尝试从站点下载 HTML 文件。我正在使用以下简单方法:

 URL url = new URL("here goes the link to the html file");
 BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
 String htmlfile = "";
 String temp;
 while ((temp = br.readLine()) != null) {
       htmlfile+= temp;
 }

问题是我在 htmlfile 变量中得到以下字符串:

The installation of ... requires the acceptance of a cookie by your browser    
software.    The cookie is used to ensure that you and only you are 
able to access information ....

换句话说,我需要在从 url 打开流时启用 cookie。是否可以通过使用 URL 来实现此目的,还是我需要其他方法?提前致谢

最佳答案

您可以使用 addRequestProperty()URLConnection 上设置 cookie对象,例如

URL url = new URL("here goes the link to the html file");
URLConnection connection = url.openConnection();
connection.addRequestProperty("Cookie", "here goes the cookie");
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));

如果 cookie 事先不知道,但是由对先前 HTTP 请求的回复设置的,那么可以使用 getHeaderFields()在代表先前 HTTP 交换的 URLConnection 实例上等以检索 cookie。

关于JAVA:如何从需要启用 cookie 的站点下载 HTML 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9471779/

相关文章:

java - 如何替换 HashMap 中的重复元素

java - Jetty ALPN/NPN 尚未正确配置

java - OkHttp,Android - 下载 html 页面并在 View 中显示此内容

javascript - 即使成功,Ajax 也没有给出响应

java - "x = x = .."(双等于/赋值)有什么特殊含义吗?

html - 将一个背景图像拆分为两个 div

使用 Cookie 的 Java Web App 安全性

JavaScript Cookie 不基于 URL 属性写入

java - CAS 单点登录过滤器

java - PKIX 路径验证失败 : java. security.cert.CertPathValidatorException:名称约束检查失败