javaokhttpcookiejar

Cookies using OkHttp


I have been working on a client in Java that makes requests to the server. Right now to keep a user logged in I need to set cookies in the same way as postman or browsers does, that is, if the server sets a cookie the client must take it in future requests directed to to this url. I currently have an http client implemented using OkHttp but if there was a better way to do it I would not mind changing the library. I have been looking and I have seen that CookieJar could be the solution for my problem but I have not found a concrete example to follow.

In short: how do I add cookies in this method to this interface to meet the objective?

Thank you very much!

public static String sendPost(Map<String,Object> messageToSend, String url) throws Exception {
    // Set requestBody as individual formatted to json
    String jsonRequest  = new Gson().toJson(messageToSend);
    RequestBody body    = RequestBody.create(jsonRequest,MediaType.parse("application/json; charset=utf-8"));

    //  Set request parameters
    Request request = new Request.Builder()
            .url("http://" + ADDR + ":" + PORT + url)
            .addHeader("User-Agent", "OkHttp Bot")
            .post(body)
            .build();

    //  Send request and get response body
    Response response = HTTP_CLIENT.newCall(request).execute();
    if (response.isSuccessful()) {
        ResponseBody responseBody = response.body();
        if (responseBody != null)
            return responseBody.string();
    }
    return null;
}

P.D.: The server sets the cookies correctly as in browsers and Postman it works like a charm.


Solution

  • At the end I changed OkHttp to HttpClient (by Apache) and it works well.

    The code I used:

    private HttpClient httpClient;
    private HttpContext httpContext = new BasicHttpContext();
    
    public MyHttpClient() {
        httpClient = HttpClientBuilder.create().build();
        httpContext.setAttribute(HttpClientContext.COOKIE_STORE, new BasicCookieStore());
    }