【问题标题】:JAVA: How can I download an HTML file from a site that requires cookies enabled?JAVA:如何从需要启用 cookie 的站点下载 HTML 文件?
【发布时间】:2012-03-17 07:48:01
【问题描述】:

我正在尝试从网站下载 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 来实现这一点,还是我需要不同的方法?提前致谢

【问题讨论】:

    标签: java html cookies


    【解决方案1】:

    您可以使用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 请求的回复设置的,则可以在代表先前 HTTP 交换的 URLConnection 实例上使用 getHeaderFields() 等来检索 cookie。

    【讨论】:

    • 没错,但如果网站要求您接受(并重新传输)cookie,那么我需要做更多的工作。
    • 没错。您可以通过使用getHeaderFields() 和朋友查看Set-Cookie 标头来读取服务器发送的cookie。
    【解决方案2】:

    如果你使用像 Apache HttpComponents 这样好的库

    http://hc.apache.org/index.html

    它会为您管理 cookie。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      • 2012-10-23
      • 1970-01-01
      • 1970-01-01
      • 2012-10-11
      • 1970-01-01
      相关资源
      最近更新 更多