java - 如何在 https 连接上检索 cookie?

标签 java cookies https jsoup

我正在尝试将 cookie 保存在使用 SSL 但始终返回 NULL 的 URL 中。

private Map<String, String> cookies = new HashMap<String, String>();

    private Document get(String url) throws IOException {
            Connection connection = Jsoup.connect(url);
            for (Entry<String, String> cookie : cookies.entrySet()) {
                connection.cookie(cookie.getKey(), cookie.getValue());
            }
            Response response = connection.execute();
            cookies.putAll(response.cookies());
            return response.parse();
        }

    private void buscaJuizado(List<Movimentacao> movimentacoes) {
            try {
                Connection.Response res = Jsoup                          .connect("https://projudi.tjpi.jus.br/projudi/publico/buscas/ProcessosParte?publico=true")
  .userAgent("Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20120716 Firefox/15.0a2")
  .timeout(0)
  .response();
  cookies = res.cookies();
  Document doc = get("https://projudi.tjpi.jus.br/projudi/listagens/DadosProcesso?  numeroProcesso=" + campo);
  System.out.println(doc.body());
  } catch (IOException ex) {
     Logger.getLogger(ConsultaProcessoTJPi.class.getName()).log(Level.SEVERE, null, ex);
  }
}

我尝试在第一次连接时捕获 cookie,但它们总是设置为 NULL。由于安全连接 (HTTPS),我认为它可能是一些 Cois 有什么想法吗?

最佳答案

问题不是 HTTPS。问题或多或少是一个小错误。

要解决您的问题,您只需将 .response() 替换为 .execute()。像这样,

private void buscaJuizado(List<Movimentacao> movimentacoes) {
  try {
    Connection.Response res = Jsoup
      .connect("https://projudi.tjpi.jus.br/projudi/publico/buscas/ProcessosParte?publico=true")
      .userAgent("Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20120716 Firefox/15.0a2")
      .timeout(0)
      .execute(); // changed fron response()
    cookies = res.cookies(); 
    Document doc = get("https://projudi.tjpi.jus.br/projudi/listagens/DadosProcesso?numeroProcesso="+campo);
    System.out.println(doc.body());
  } catch (IOException ex) {
    Logger.getLogger(ConsultaProcessoTJPi.class.getName()).log(Level.SEVERE, null, ex);
  }
}


总的来说,您必须确保先执行请求。
调用 .response() 有助于获取 Connection.Response 对象 after 请求已被执行。显然,如果您还没有执行请求,Connection.Response 对象将不会很有用。

事实上,如果您尝试在未执行的响应上调用 res.body(),您将收到以下异常指示问题。

java.lang.IllegalArgumentException: Request must be executed (with .execute(), .get(), or .post() before getting response body

关于java - 如何在 https 连接上检索 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12533310/

相关文章:

javascript - 如何在响应中同时发送 cookie 和重定向? (无服务器框架)

ssl - Silverlight 2.0 中 SLL Uri 的 HttpWebRequest

Apache 无法启动 - 试图找到 HTTP 站点的 key

java - 除非满足条件,否则阻止从按钮组中的特定切换按钮进行切换

java - JPA Hibernate Maven 测试 --> 未知类

java - 使用 SQL Server 2005/2008 的最新 jdbc 驱动程序时,准备好的语句、 View 和存储过程的性能比较如何?

javascript - Set-Cookie 被阻止,因为它的 Domain 属性对于当前主机 url 无效

javascript - 设置cookie并显示cookie的值

angular - 如何修复 xhr2-cookies 中的 "module not found error"

java - 关于如何在 Java 中解决这个棘手问题的建议