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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24263921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:57:19  来源:igfitidea点击:

How to implement cookie handling on Android using OkHttp?

androidcookiesokhttp

提问by Daniel

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

通过 Square https://github.com/square/okhttp使用 OkHttp ,我该如何:

  1. Retrieve a cookie returned from the server
  2. Store the cookie for upcoming requests
  3. Use the stored cookie in subsequent requests
  4. Update the cookie returned by the subsequent request
  1. 检索从服务器返回的 cookie
  2. 为即将到来的请求存储 cookie
  3. 在后续请求中使用存储的 cookie
  4. 更新后续请求返回的cookie

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

理想情况下,cookie 将随每个请求自动存储、重新发送和更新。

回答by hidro

For OkHttp3, a simple accept-all, non-persistent CookieJarimplementation can be as follows:

对于 OkHttp3,一个简单的全接受、非持久性CookieJar实现可以如下所示:

OkHttpClient client = new OkHttpClient.Builder()
    .cookieJar(new CookieJar() {
        private final HashMap<HttpUrl, List<Cookie>> cookieStore = new HashMap<>();

        @Override
        public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
            cookieStore.put(url, cookies);
        }

        @Override
        public List<Cookie> loadForRequest(HttpUrl url) {
            List<Cookie> cookies = cookieStore.get(url);
            return cookies != null ? cookies : new ArrayList<Cookie>();
        }
    })
    .build();

Or if you prefer to use java.net.CookieManager, include okhttp-urlconnectionin your project, which contains JavaNetCookieJar, a wrapper class that delegates to java.net.CookieHandler:

或者,如果您更喜欢使用java.net.CookieManager,请包含okhttp-urlconnection在您的项目中,该项目包含JavaNetCookieJar一个委托给 的包装类java.net.CookieHandler

dependencies {
    compile "com.squareup.okhttp3:okhttp:3.0.0"
    compile "com.squareup.okhttp3:okhttp-urlconnection:3.0.0"
}


CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
OkHttpClient client = new OkHttpClient.Builder()
    .cookieJar(new JavaNetCookieJar(cookieManager))
    .build();

回答by Miguel Lavigne

Pre OkHttp 3, 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.

在 OkHttp 3 之前,您可以将 CookieHandler 传递给您的 OkHttpClient 实例。您可以使用 java.net 中的 CookieManager 实现,也可以根据需要实现自己的实现。选择最适合您需求的策略。

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

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.

OkHttp 会将从 Responses 接收到的 cookie 保存到 CookieHandler 中,并在发送请求时从中读取。它将这样做以匹配请求/响应 URI。

回答by hmac

I needed to share the default Cookie Jar (CookieManager.getInstance()) so this seemed to work ok for me.

我需要共享默认的 Cookie Jar (CookieManager.getInstance()) 所以这对我来说似乎没问题。

return new CookieJar() {

        @Override
        public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
            CookieManager cookieManager = CookieManager.getInstance();

            for (Cookie cookie : cookies) {
                cookieManager.setCookie(url.toString(), cookie.toString());
            }
        }

        @Override
        public List<Cookie> loadForRequest(HttpUrl url) {
            CookieManager cookieManager = CookieManager.getInstance();
            List<Cookie> cookies = new ArrayList<>();
            if (cookieManager.getCookie(url.toString()) != null) {
                String[] splitCookies = cookieManager.getCookie(url.toString()).split("[,;]");
                for (int i=0; i<splitCookies.length; i++) {
                    cookies.add(Cookie.parse(url, splitCookies[i].trim()));
                }
            }
            return cookies;
        }
    };