user1689105
user1689105

Reputation: 31

How to retrieve cookies on a https connection?

I'm trying to save the cookies in a URL that uses SSL but always return NULL.

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);
  }
}

I try to capture the cookies the first connection, but always they are always set to NULL. I think it might be some Cois because of the secure connection (HTTPS) Any idea?

Upvotes: 3

Views: 1207

Answers (1)

Jared Paolin
Jared Paolin

Reputation: 247

The issue is not HTTPS. The problem is more or less a small mistake.

To fix your issue you can simply replace .response() with .execute(). Like so,

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);
  }
}


Overall you have to make sure you execute the request first.
Calling .response() is useful to grab the Connection.Response object after the request has already been executed. Obviously the Connection.Response object won't be very useful if you haven't executed the request.

In fact if you were to try calling res.body() on the unexecuted response you would receive the following exception indicating the issue.

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

Upvotes: 1

Related Questions