【发布时间】: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 中一样,它就像一个魅力。
【问题讨论】:
-
这能回答你的问题吗? Automatic cookie handling with OkHttp 3