在做项目的时候,我们可能有两个Activity——Activity A和Activity B,这时候我们在这两个Activity中都有网络请求的需求,于是,我们引入OkHttp的包来进行网络连接:

compile 'com.squareup.okhttp3:okhttp:3.7.0'     //网络请求

然后,如果我们是在两个Activity中需要对同一个页面处理数据怎么办呢,首先需要确定的是,需要用到Cookie,于是有提到使用Cookie持久化的问题,但是,很多时候并不需要对Cookie持久化,只需传递一个Cookie即可

查阅文档可知,Android在两个Activity之间传递数据用的是Intent,因为没有Cookie这种类型,所以我们必须把Cookie转化为对象才可以传递,在传递对象的时候要注意,传递的对象必须实现了序列化接口才可以,所以我们可以这么写

首先我们定义一个HttpHelper类:

package me.hebin.suda;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

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

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class HttpHelper {
    private static final MediaType JSON  = MediaType.parse("application/json; charset=utf-8");
    private static final MediaType Form  = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
    private OkHttpClient okHttpClient;
    private List<Cookie> cookieList;

    public List<Cookie> getCookieList() {
        return cookieList;
    }

    public void setCookieList(List<Cookie> cookieList) {
        this.cookieList = cookieList;
    }

    public HttpHelper(){
        okHttpClient = new OkHttpClient.Builder()
        .cookieJar(new CookieJar() {
            @Override
            public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
                cookieList = list;
            }

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

    String DoGet(String url){
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = okHttpClient.newCall(request).execute()) {
            return response.body().string();
        }
        catch(IOException e){
            return "";
        }
    }

    String DoPostJson(String url, String json){
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            return response.body().string();
        }
        catch(IOException e){
            return "";
        }
    }

    String DoPostForm(String url, HashMap<String,String> form){
        FormBody.Builder body=new FormBody.Builder();
        for (String key : form.keySet()) {
            body.add(key, form.get(key));
        }
        Request request = new Request.Builder()
                .url(url)
                .post(body.build())
                .build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            return response.body().string();
        }
        catch(IOException e){
            return "";
        }
    }

    Bitmap GetValid(String url){
        Bitmap bitmap = null;
        try {
            //获取请求对象
            Request request = new Request.Builder().url(url).build();

            //获取响应体
            ResponseBody body = okHttpClient.newCall(request).execute().body();

            //获取流
            InputStream in = body.byteStream();
            //转化为bitmap
            bitmap = BitmapFactory.decodeStream(in);
        }
        catch (IOException e){

        }
        return bitmap;
    }
}

定义一个实现序列化的OkHttpCookie类:

package me.hebin.suda;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import okhttp3.Cookie;

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

以及这个类的List数组实现:

package me.hebin.suda;

import java.io.Serializable;
import java.util.ArrayList;

public class SerializableOkHttpCookiesArray implements Serializable{
    ArrayList<SerializableOkHttpCookies> arrayList = new ArrayList<SerializableOkHttpCookies>();

    public ArrayList<SerializableOkHttpCookies> getArrayList() {
        return arrayList;
    }

    public void setArrayList(ArrayList<SerializableOkHttpCookies> arrayList) {
        this.arrayList = arrayList;
    }
}

然后在Activity A中:

private ArrayList<SerializableOkHttpCookies> toArrayList(List<Cookie> list){
    ArrayList<SerializableOkHttpCookies> objlist = new ArrayList<SerializableOkHttpCookies>();
    for(Cookie e : list){
        objlist.add(new SerializableOkHttpCookies(e));
    }
    return objlist;
}

在Activity B中:

private List<Cookie> toList(ArrayList<SerializableOkHttpCookies> list){
    List<Cookie> objlist = new ArrayList<Cookie>();
    for(SerializableOkHttpCookies e : list){
        objlist.add(e.getCookies());
    }
    return objlist;
}

A传值:

Bundle bundle = new Bundle();
bundle.putSerializable("cookie", toArrayList(httpHelper.getCookieList()));
intent.putExtras(bundle);

startActivity(intent);

B接收:

Intent intent = getIntent();
Bundle bundle = intent.getExtras();
httpHelper.setCookieList(toList((ArrayList<SerializableOkHttpCookies>) bundle.getSerializable("cookie")));

结束收工,完美 (乛◡乛)

小广告:关于获取西普实验吧所有Writeup请点击这里查看索引

查看所有Flag需要付费,需要获取所有Flag的童鞋请访问这里成为付费用户,可以自助把自己的注册邮箱加入网站白名单,即可免回复看到本站所有Flag

Flag大全地址:所有Flag

PS:本站不是实验吧的官方站点,纯粹是个人博客,收取Flag费用仅是维持服务器费用,做站不易,且行窃珍惜,如果喜欢我的博客,愿意捐赠的,可以扫描下面的二维码

微信二维码:
支付宝二维码: