OKHttp3学习笔记-Http Session

来源:互联网 发布:网络经营保健食品 编辑:程序博客网 时间:2024/05/20 07:51

Session一般是在Web应该中使用的东西,最早我参与的项目都不需要用到Session。但是实际上,很多应用要使用到Session的。
在Web应用中,Session是通过Cookie传递的,在第一次访问网页的时候,如果服务端开启了Session,则在返回信息中会携带Session信息,当之后再访问网页,请求中都会带着Session信息。
用我自己的php服务端展示的话如下所示。
第一次请求,Request中不包含Session信息

GET http://localhost/index/index/index HTTP/1.1Host: localhostConnection: keep-aliveUpgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8Accept-Encoding: gzip, deflate, brAccept-Language: zh-CN,zh;q=0.8Cookie: pgv_pvi=6689128448; Phpstorm-ba9458cf=5f1ce810-71dc-4a40-821d-4699b7059873

第一次请求后的返回,在set-Cookie中带着Session信息

HTTP/1.1 200 OKDate: Thu, 31 Aug 2017 03:25:01 GMTServer: Apache/2.4.23 (Win64) PHP/5.6.25X-Powered-By: PHP/5.6.25Set-Cookie: PHPSESSID=t45gjqibrtjsjooe6hlkric6v4; path=/Expires: Thu, 19 Nov 1981 08:52:00 GMTCache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0Pragma: no-cacheContent-Length: 566Keep-Alive: timeout=5, max=100Connection: Keep-AliveContent-Type: text/html; charset=utf-8

刷新页面后的请求中,就已经带着Session信息了

GET http://localhost/index/index/index HTTP/1.1Host: localhostConnection: keep-aliveCache-Control: max-age=0Upgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8Accept-Encoding: gzip, deflate, brAccept-Language: zh-CN,zh;q=0.8Cookie: pgv_pvi=6689128448; Phpstorm-ba9458cf=5f1ce810-71dc-4a40-821d-4699b7059873; PHPSESSID=t45gjqibrtjsjooe6hlkric6v4

以上关于Session的信息保存和使用(实际是Cookie)都是由浏览器完成的,但是在Android开发的时候,我们没有浏览器帮我们做这些工作,怎么办呢?OKHttp3提供了方便的接口用来对Cookie进行操作。

val okHttpClient = OkHttpClient().newBuilder().cookieJar(object: CookieJar{    val cookieStore = PersistentCookieStore(getApplicationContext())    override fun saveFromResponse(url: HttpUrl, cookies: MutableList<Cookie>) {        for(cookie in cookies){            cookieStore.add(url, cookie)    }    }    override fun loadForRequest(url: HttpUrl): MutableList<Cookie> {        val cookies = cookieStore.get(url)        return cookies?: mutableListOf<Cookie>()    }}).build()

loadForRequest会在请求发出前被调用,cookie就是在这里被添加到请求里的,saveFromResponse会在返回时调用,如果要持久化cookie就要在这里进行操作了。
持久化cookie用的是从PersistentCookieStore和SerializableOkHttpCookies,这两个类需要自己添加到工程中,实现如下(代码来自于网络,亲测没问题)

public class SerializableOkHttpCookies implements Serializable {    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();    }}
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<>();        //将持久化的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<>();        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<>();        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;    }}

相比于之前的请求,现在第一次进入页面的请求如下:

GET http://192.168.9.80/index/index/index HTTP/1.1Host: 192.168.9.80Connection: Keep-AliveAccept-Encoding: gzipUser-Agent: okhttp/3.8.1

刷新是,请求中就带着Session的内容了

GET http://192.168.9.80/index/index/index HTTP/1.1Host: 192.168.9.80Connection: Keep-AliveAccept-Encoding: gzipCookie: PHPSESSID=3ignhso5d41h591f0nn4cduhf4User-Agent: okhttp/3.8.1
原创粉丝点击