【问题标题】:How to retrieve cookies on a https connection?如何在 https 连接上检索 cookie?
【发布时间】:2012-09-14 00:58:09
【问题描述】:

我正在尝试将 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 有什么想法吗?

【问题讨论】:

    标签: java cookies https jsoup


    【解决方案1】:

    问题不在于 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 对象很有用。显然,如果您没有执行请求,Connection.Response 对象将不会很有用。

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

    java.lang.IllegalArgumentException:请求必须执行(使用 .execute()、.get() 或 .post() 才能获得响应正文

    【讨论】:

      猜你喜欢
      • 2017-02-27
      • 2015-04-02
      • 2014-04-20
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      • 2011-09-18
      • 1970-01-01
      相关资源
      最近更新 更多