OkHttp保存和使用cookie

本文介绍如何使用OkHttp进行Cookie的持久化管理,包括创建CookieManager类来处理Cookie的加载和保存,以及使用PersistentCookieStore类来实现Cookie在本地的存储与读取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. client.cookieJar()用来设置cookie

 OkHttpClient okHttpClient = new OkHttpClient.Builder()
                //打印日志

                .addInterceptor(interceptor)

                //设置Cache目录
                .cache(cache(context))

                //失败重连
                .retryOnConnectionFailure(true)

                //time out
                .readTimeout(60000, TimeUnit.SECONDS)
                .connectTimeout(60000, TimeUnit.SECONDS)

                //缓存cookie
                .cookieJar(new CookieManager(context))
                .build();

其中cookieManager的代码为:

public class CookieManager implements CookieJar{
    Context context;
     private  PersistentCookieStore cookieStore ;
     public CookieManager(Context context) {
        // TODO Auto-generated constructor stub
         this.context=context;
         cookieStore= new PersistentCookieStore(context);
    }
    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {
        List<Cookie> cookies = cookieStore.get(url);
        return cookies;
    }

    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
        // TODO Auto-generated method stub
        if (cookies != null && cookies.size() > 0) {
            for (Cookie item : cookies) {
                cookieStore.add(url, item);
            }
        }
    }

}

2. CookieMaager中需要两个辅助类,用来保存cookie


第一个辅助类


public class PersistentCookieStore {
    private static final String LOG_TAG = "PersistentCookieStore";
    private static final String COOKIE_PREFS = "Cookies_Prefs";

    private final Map<String, ConcurrentHashMap<String, Cookie>> cookies;
    private final SharedPreferences cookiePrefs;

    public PersistentCookieStore(Context context) {
        cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
        cookies = new HashMap<String, ConcurrentHashMap<String, Cookie>>();

        //���־û���cookies���浽�ڴ��� ��map cookies
        Map<String, ?> prefsMap = cookiePrefs.getAll();
        for (Map.Entry<String, ?> entry : prefsMap.entrySet()) {
            String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
            for (String name : cookieNames) {
                String encodedCookie = cookiePrefs.getString(name, null);
                if (encodedCookie != null) {
                    Cookie decodedCookie = decodeCookie(encodedCookie);
                    if (decodedCookie != null) {
                        if (!cookies.containsKey(entry.getKey())) {
                            cookies.put(entry.getKey(), new ConcurrentHashMap<String, Cookie>());
                        }
                        cookies.get(entry.getKey()).put(name, decodedCookie);
                    }
                }
            }
        }
    }

    protected String getCookieToken(Cookie cookie) {
        return cookie.name() + "@" + cookie.domain();
    }

    public void add(HttpUrl url, Cookie cookie) {
        String name = getCookieToken(cookie);

        //��cookies���浽�ڴ��� ���������� �����ô�cookie
        if (!cookie.persistent()) {
            if (!cookies.containsKey(url.host())) {
                cookies.put(url.host(), new ConcurrentHashMap<String, Cookie>());
            }
            cookies.get(url.host()).put(name, cookie);
        } else {
            if (cookies.containsKey(url.host())) {
                cookies.get(url.host()).remove(name);
            }
        }

        //��cookies�־û�������
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));
        prefsWriter.putString(name, encodeCookie(new SerializableOkHttpCookies(cookie)));
        prefsWriter.apply();
    }

    public List<Cookie> get(HttpUrl url) {
        ArrayList<Cookie> ret = new ArrayList<Cookie>();
        if (cookies.containsKey(url.host()))
            ret.addAll(cookies.get(url.host()).values());
        return ret;
    }

    public boolean removeAll() {
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        prefsWriter.clear();
        prefsWriter.apply();
        cookies.clear();
        return true;
    }

    public boolean remove(HttpUrl url, Cookie cookie) {
        String name = getCookieToken(cookie);

        if (cookies.containsKey(url.host()) && cookies.get(url.host()).containsKey(name)) {
            cookies.get(url.host()).remove(name);

            SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
            if (cookiePrefs.contains(name)) {
                prefsWriter.remove(name);
            }
            prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));
            prefsWriter.apply();

            return true;
        } else {
            return false;
        }
    }

    public List<Cookie> getCookies() {
        ArrayList<Cookie> ret = new ArrayList<Cookie>();
        for (String key : cookies.keySet())
            ret.addAll(cookies.get(key).values());

        return ret;
    }

    /**
     * cookies ����� string
     *
     * @param cookie Ҫ���л���cookie
     * @return ���л�֮���string
     */
    protected String encodeCookie(SerializableOkHttpCookies cookie) {
        if (cookie == null)
            return null;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(os);
            outputStream.writeObject(cookie);
        } catch (IOException e) {
            Log.d(LOG_TAG, "IOException in encodeCookie", e);
            return null;
        }

        return byteArrayToHexString(os.toByteArray());
    }

    /**
     * ���ַ��������л���cookies
     *
     * @param cookieString cookies string
     * @return cookie object
     */
    protected Cookie decodeCookie(String cookieString) {
        byte[] bytes = hexStringToByteArray(cookieString);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        Cookie cookie = null;
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            cookie = ((SerializableOkHttpCookies) objectInputStream.readObject()).getCookies();
        } catch (IOException e) {
            Log.d(LOG_TAG, "IOException in decodeCookie", e);
        } catch (ClassNotFoundException e) {
            Log.d(LOG_TAG, "ClassNotFoundException in decodeCookie", e);
        }

        return cookie;
    }

    /**
     * ����������תʮ�������ַ���
     *
     * @param bytes byte array to be converted
     * @return string containing hex values
     */
    protected String byteArrayToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte element : bytes) {
            int v = element & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString().toUpperCase(Locale.US);
    }

    /**
     * ʮ�������ַ���ת����������
     *
     * @param hexString string of hex-encoded values
     * @return decoded byte array
     */
    protected byte[] hexStringToByteArray(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
        }
        return data;
    }

第二个辅助类

public class SerializableOkHttpCookies implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private transient final Cookie cookies;
    private transient Cookie clientCookies;

    public SerializableOkHttpCookies(Cookie cookies) {
        this.cookies = cookies;
    }

    public Cookie getCookies() {
        Cookie bestCookies = cookies;
        if (clientCookies != null) {
            bestCookies = clientCookies;
        }
        return bestCookies;
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        out.writeObject(cookies.name());
        out.writeObject(cookies.value());
        out.writeLong(cookies.expiresAt());
        out.writeObject(cookies.domain());
        out.writeObject(cookies.path());
        out.writeBoolean(cookies.secure());
        out.writeBoolean(cookies.httpOnly());
        out.writeBoolean(cookies.hostOnly());
        out.writeBoolean(cookies.persistent());
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        String name = (String) in.readObject();
        String value = (String) in.readObject();
        long expiresAt = in.readLong();
        String domain = (String) in.readObject();
        String path = (String) in.readObject();
        boolean secure = in.readBoolean();
        boolean httpOnly = in.readBoolean();
        boolean hostOnly = in.readBoolean();
        boolean persistent = in.readBoolean();
        Cookie.Builder builder = new Cookie.Builder();
        builder = builder.name(name);
        builder = builder.value(value);
        builder = builder.expiresAt(expiresAt);
        builder = hostOnly ? builder.hostOnlyDomain(domain) : builder.domain(domain);
        builder = builder.path(path);
        builder = secure ? builder.secure() : builder;
        builder = httpOnly ? builder.httpOnly() : builder;
        clientCookies =builder.build();
    }
}
<think>好的,我现在需要给用户介绍OkHttp使用。首先,我得回忆一下OkHttp的基本概念,它是一个用于AndroidJava应用的HTTP客户端,对吧?对,由Square公司开发,现在好像由SquareGoogle共同维护了。 接下来,用户可能想知道为什么要用OkHttp,所以需要列出它的优点,比如支持HTTP/2、连接池、GZIP压缩、缓存这些功能。还有,它简化了网络请求的处理,比如同步异步请求,拦截器之类的。不过要确保这些信息准确,可能需要查证一下最新的文档。 然后,用户可能需要具体的步骤来开始使用OkHttp。应该先讲如何引入依赖,比如在Gradle中添加implementation 'com.squareup.okhttp3:okhttp:4.x.x',这里要提醒用户替换成最新版本,但版本号需要确认是否正确,比如现在最新的是4.12.0吗?或者有没有更高的?可能需要检查一下Maven仓库或者官方文档。 接下来,基本的GET请求示例。需要展示同步异步的用法。同步请求是在子线程中执行,而异步是通过enqueue方法,用Callback来处理结果。这里要注意代码的正确性,比如OkHttpClient的实例创建,Request的构建,以及回调中的onResponseonFailure方法。需要提到响应处理要在子线程进行,不能在主线程更新UI,否则会崩溃。 然后是POST请求的例子,需要构造RequestBody,比如使用FormBody来发送表单数据,或者用MultipartBody发送文件。这部分要展示如何添加参数,设置MediaType,并正确构建请求体。同时,要提到如何设置请求头,比如Content-Type,但要注意OkHttp可能自动处理一些头信息。 接下来,高级特性部分,拦截器是一个重点。需要解释拦截器的用途,比如添加公共参数、日志记录、重试机制。可以给出一个日志拦截器的例子,使用HttpLoggingInterceptor,并说明如何添加到OkHttpClient中。同时,自定义拦截器的实现步骤,比如实现Interceptor接口,处理chain.request()chain.proceed()。 缓存部分需要说明如何配置缓存目录大小,使用Cache类,并添加到OkHttpClient的配置中。这里要注意缓存策略可能需要服务器支持,或者通过请求头控制。 文件上传下载的例子,可能需要展示MultipartBody的使用,以及如何通过ResponseBody写入文件。下载文件的时候,要提醒用户处理IO异常,以及确保文件保存路径的正确性。 最后,注意事项部分,需要强调网络请求要在子线程执行,或者在主线程使用异步方式。还有,在AndroidManifest中添加网络权限,处理生命周期防止内存泄漏,比如取消请求。此外,可能提到Https的证书验证问题,以及如何信任所有证书(但提醒这不安全,仅用于测试)。 在结构上,应该先概述OkHttp,然后分步骤讲解基本使用、高级特性、文件处理,最后注意事项。代码示例要正确,用正确的缩进语法,避免错误。同时,使用中文解释,确保用户容易理解。需要检查是否有过时的API,比如OkHttp3OkHttp4之间的差异,比如在版本4中是否弃用了某些方法,或者回调的处理是否有变化。例如,在4.x版本中,回调是否仍然在子线程执行,是否需要手动切换线程更新UI。 可能还需要提到其他功能,比如WebSocket的支持,或者Cookie的管理,但根据用户的提问深度,可能不需要展开。总之,要确保回答全面且重点突出,帮助用户快速上手OkHttp的基础常用功能。</think>以下是对OkHttp的详细介绍,采用清晰的模块化结构说明: --- ### 一、OkHttp概述 由Square公司开发并维护的**高效HTTP客户端**,适用于Android/Java应用,特点包括: - 支持HTTP/2协议 - 内置连接池(减少延迟) - 透明GZIP压缩(节省流量) - 响应缓存(减少重复请求) - 拦截器链(灵活扩展) --- ### 二、基础使用 #### 1. 添加依赖 Gradle配置: ```groovy dependencies { implementation 'com.squareup.okhttp3:okhttp:4.12.0' // 2023年最新稳定版 } ``` #### 2. GET请求示例 **同步请求**(需在子线程执行): ```java OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://api.example.com/data") .build(); try (Response response = client.newCall(request).execute()) { if (response.isSuccessful()) { String result = response.body().string(); // 处理结果 } } catch (IOException e) { e.printStackTrace(); } ``` **异步请求**(自动切换线程): ```java client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // 处理失败 } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { final String result = response.body().string(); // 需手动切回主线程更新UI } } }); ``` #### 3. POST请求 发送表单数据: ```java RequestBody formBody = new FormBody.Builder() .add("username", "admin") .add("password", "123456") .build(); Request request = new Request.Builder() .url("https://api.example.com/login") .post(formBody) .build(); ``` --- ### 三、高级特性 #### 1. 拦截器应用 **日志拦截器**(需额外依赖): ```groovy implementation 'com.squareup.okhttp3:logging-interceptor:4.12.0' ``` 配置示例: ```java HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); // 显示完整请求信息 OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(logging) .build(); ``` **自定义拦截器**(添加统一请求头): ```java class AuthInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request original = chain.request(); Request modified = original.newBuilder() .header("Authorization", "Bearer token") .build(); return chain.proceed(modified); } } ``` #### 2. 缓存配置 ```java File cacheDir = new File(context.getCacheDir(), "okhttp_cache"); int cacheSize = 10 * 1024 * 1024; // 10MB OkHttpClient client = new OkHttpClient.Builder() .cache(new Cache(cacheDir, cacheSize)) .build(); ``` --- ### 四、文件处理 #### 1. 文件上传 ```java MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); RequestBody fileBody = RequestBody.create(new File("/sdcard/avatar.png"), MEDIA_TYPE_PNG); RequestBody multipartBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", "avatar.png", fileBody) .build(); ``` #### 2. 文件下载 ```java try (Response response = client.newCall(request).execute()) { if (response.isSuccessful()) { try (InputStream is = response.body().byteStream(); FileOutputStream fos = new FileOutputStream("downloaded.jpg")) { byte[] buffer = new byte[2048]; int len; while ((len = is.read(buffer)) != -1) { fos.write(buffer, 0, len); } } } } ``` --- ### 五、注意事项 1. **线程管理**:同步请求需自行管理线程,异步回调默认在子线程执行 2. **网络权限**:AndroidManifest需添加: ```xml <uses-permission android:name="android.permission.INTERNET"/> ``` 3. **生命周期**:Activity销毁时调用`call.cancel()`避免内存泄漏 4. **HTTPS安全**:生产环境应配置SSL证书,测试可用: ```java .hostnameVerifier((hostname, session) -> true) // 慎用! ``` --- 通过上述模块化说明,开发者可快速掌握OkHttp的核心用法。建议结合[官方文档](https://square.github.io/okhttp/)深入了解更多高级功能。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值