android OkHttp cookie 管理

android OkHttp cookie 管理

我现在有这样一个需求,写一个刷单APP,需要爬第三方平台的数据,大部分第三方网站登录权限都是使用 cookie 来做的,当我使用 OKHttp 时,发现它默认没有对 cookie 进行管理。可以通过 CookieJar 来实现:

package com.example.a01_webview;

import android.util.Log;
import android.webkit.JavascriptInterface;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AndroidToJS extends Object {
    private String TAG = "AndroidToJS";

    // Cookie 管理
    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .cookieJar(new CookieJar() {
                @Override
                public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
                   // 从响应头中保存 cookie  
                    cookieStore.put(httpUrl.host(), list);
                }

                @Override
                public List<Cookie> loadForRequest(HttpUrl httpUrl) {
                    // 添加 cookie  
                    List<Cookie> cookies = cookieStore.get(httpUrl.host());
                    return cookies != null ? cookies : new ArrayList<Cookie>();
                }
            })
            .build();

    @JavascriptInterface
    public void hello(String msg) {
        System.out.println("JS调用了Android的hello方法: " + msg);
    }

    /**
     * @desc 登录获取 cookie
     * @param configStr Http request config
     */
    @JavascriptInterface
    public void request(String configStr) {
        RequestBody requestBody = new FormBody.Builder()
                .add("mobile", "xxx")
                .add("password", "xxx")
                .add("code", "")
                .build();

        Request request = new Request.Builder()
                .url("https://m.kd321.cn/mobile/Login.aspx")
                .post(requestBody)
                .build();

        AndroidToJS mContext = this;

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }
                Log.d(TAG, "onResponse: " + response.body().string());
                mContext.getTask();
            }
        });
    }

    /**
     * @desc 使用 cookie 获取任务列表
     */
    public void getTask() {
        String url = "https://m.kd321.cn/mobile/tasklistLiuLiang.aspx";
        final Request request = new Request.Builder().get().url(url).build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }
                Log.d(TAG, "onResponse: " + response.body().string());
            }
        });
    }
}

备注:这里封装的方法,提供会给 WebView 使用

posted on 2020-12-15 17:11  manbax  阅读(1023)  评论(0编辑  收藏  举报