OkHttp3登录并保存cookie

为了方便以后再次使用做个简单的记录

1.在MyApplication中声明OKHttpClient方便以后再应用中任何地方的调用

private OkHttpClient client;
public OkHttpClient getClient() {
    return client;
}

public void setClient(OkHttpClient client) {
    this.client = client;
}

2.在LoginAvtivity内创建OKhttpclient对象并使用OKhttp的cookie自动管理功能

private HashMap,List> cookieStore=new HashMap<>();

client = new OkHttpClient.Builder().connectTimeout(1000*10, TimeUnit.SECONDS).cookieJar(new CookieJar() {
    @Override
    public void saveFromResponse(HttpUrl url, List cookies) {
        cookieStore.put(url, cookies);
        cookieStore.put(HttpUrl.parse(AppConfig.LOGIN), cookies);
        for(Cookie cookie:cookies){
            System.out.println("cookie Name:"+cookie.name());
            System.out.println("cookie Path:"+cookie.path());
        }
    }
    @Override
    public List loadForRequest(HttpUrl url) {
        List cookies = cookieStore.get(HttpUrl.parse(AppConfig.LOGIN));
        if(cookies==null){
            System.out.println("没加载到cookie");
        }
        return cookies != null ? cookies : new ArrayList();
    }
}).build();
3.执行登录操作

Map, String> map = new HashMap<>();
map.put("username", email);
map.put("password", password);
Callback callback = new Callback() {
    public void onFailure(Call call, IOException e) {

    }

    public void onResponse(Call call, Response response) throws IOException {

        myApplication.setClient(client);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showProgress(false);
            }
        });
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        LoginActivity.this.finish();
    }
};
MyHttpClient.sendAnysPost(client,AppConfig.LOGIN, callback, map);
4.请求使用的OKhttp的简单封装

import java.util.Map;

import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * 封装OKhttp
 * Created by PC on 2017/8/8.
 */
public class MyHttpClient {

    public static void sendAnysGet(OkHttpClient client,String url,Callback callback){
        Request request = new Request.Builder().url(url).get().build();
        client.newCall(request).enqueue(callback);
    }

    public static void sendAnysPost(OkHttpClient client,String url,Callback callback,Map,String> map){
        FormBody.Builder builder = new  FormBody.Builder();
        if (map!=null)
        {
            for (Map.Entry,String> entry:map.entrySet())
            {
                builder.add(entry.getKey(),entry.getValue());
            }
        }
        FormBody body = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        client.newCall(request).enqueue(callback);
    }
}




你可能感兴趣的:(OkHttp3登录并保存cookie)