【问题标题】:Cookies using OkHttp [duplicate]使用 OkHttp 的 Cookie [重复]
【发布时间】:2020-06-19 00:10:42
【问题描述】:

我一直在使用 Java 开发一个向服务器发出请求的客户端。现在要让用户保持登录状态,我需要以与邮递员或浏览器相同的方式设置 cookie,也就是说,如果服务器设置了一个 cookie,客户端必须在将来指向此 url 的请求中接受它。我目前有一个使用 OkHttp 实现的 http 客户端,但如果有更好的方法,我不介意更改库。我一直在寻找,发现 CookieJar 可以解决我的问题,但我还没有找到具体的例子。

简而言之:如何将这个方法中的cookies添加到这个接口中来达到目的?

非常感谢!

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.:服务器正确设置 cookie,就像在浏览器和 Postman 中一样,它就像一个魅力。

【问题讨论】:

标签: java okhttp cookiejar


【解决方案1】:

最后,我将 OkHttp 更改为 HttpClient(由 Apache 提供),它运行良好。

我使用的代码:

private HttpClient httpClient;
private HttpContext httpContext = new BasicHttpContext();

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

【讨论】:

    猜你喜欢
    • 2016-04-25
    • 2014-10-25
    • 1970-01-01
    • 2021-09-19
    • 2020-12-03
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 2014-08-07
    相关资源
    最近更新 更多