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