4

I noticed that using unirest java library cookies are by default sent in requests after being set in responses (just like any browser does). Is there any way to avoid it?

Example:

public class Main {
    private static HttpResponse<JsonNode> doRequest() throws UnirestException {
        try {
            HttpResponse<JsonNode> jsonResponse = Unirest
                    .get("http://example.com")
                    .header("Accept", "application/json").asJson();
            return jsonResponse;
        } catch (UnirestException e) {
            throw e;
        }

    }
    public static void main(String[] args) throws UnirestException {
        //first request receive a set-cookie header in response
        doRequest();
        //second request send a Cookie header with the cookie set by the first one: can I avoid this?
        doRequest();
    }
}
Zac
  • 2,180
  • 2
  • 23
  • 36
  • 1
    IMHO it's a shame that: 1) two visually independent pieces of code are connected through the statically saved state; 2) such behaviour (cookies storing) is enabled by default. This is both unexpected for the developer and unsafe because shared state can lead to the upredictable behaviour of the app. And Unirest's configuration is managed through the static setters as well. That's why I've stopped using Unirest. – Ilya Serbis Mar 17 '19 at 19:21

2 Answers2

6

It is probably due to a default setting on the underlying HttpClient implementation. Setting a custom HttpClient seems to work:

HttpClient httpClient = HttpClients.custom()
    .disableCookieManagement()
    .build();
Unirest.setHttpClient(httpClient);
Zac
  • 2,180
  • 2
  • 23
  • 36
3

Looks like

Unirest.config().enableCookieManagement(false);

solves the problem.

Ilya Serbis
  • 21,149
  • 6
  • 87
  • 74