本文介绍了如何在Android上使用OkHttp实现cookie处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Square的OkHttp ,我如何:

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


  1. 检索服务器返回的Cookie

  2. 存储即将到来的请求的cookie

  3. 在后续请求中使用存储的cookie

  4. 更新后续请求返回的cookie

  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



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

推荐答案

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

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

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();

或者如果您喜欢使用 java.net.CookieManager ,在您的项目中包含 okhttp-urlconnection ,其中包含 JavaNetCookieJar ,一个包装类, c $ c> java.net.CookieHandler :

Or if you prefer to use java.net.CookieManager, include okhttp-urlconnection in your project, which contains JavaNetCookieJar, a wrapper class that delegates to 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();

这篇关于如何在Android上使用OkHttp实现cookie处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 07:12