如何使用OkHttp实现在Android cookie处理?如何使用、OkHttp、cookie、Android

2023-09-05 10:48:34 作者:真心不如真鈔

使用OkHttp由广场 https://github.com/square/okhttp ,哪能:

Using OkHttp by Square https://github.com/square/okhttp, how can I:

从服务器返回一个cookie 在商店为即将到来的请求的cookie 使用在后续请求中存储的cookie 更新的后续请求返回的cookie

在理想情况下该cookie将被存储,怨恨,并与每一个请求自动更新。

Ideally the cookie would be stored, resent and updated automatically with every request.

推荐答案

您可以传递的CookieHandler您OkHttpClient实例。您可以使用CookieManager实现从java.net或者你可以实现你自己的,如果你想要的。选择更适合您的需求最有效的策略。

You can pass a CookieHandler to your OkHttpClient instance. You can use the CookieManager implementation from java.net or you could implement your own if you want. Choose the policy that works best for your needs.

OkHttpClient client = new OkHttpClient();
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
client.setCookieHandler(cookieManager);

OkHttp将节省从反应到的CookieHandler收到饼干,并从中发送请求时读取。为此,它将匹配请求/响应的URI。

OkHttp will save cookies received from Responses into the CookieHandler and read from it when sending requests. It will do so for matching request/response URIs.