安卓笔记侠

专注安卓开发

导航

okhttp3带cookie请求

Request经常都要携带Cookie,上面说过request创建时可以通过header设置参数,Cookie也是参数之一。就像下面这样:

Request request = new Request.Builder()
    .url(url)
    .header("Cookie", "xxx")
    .build();

然后可以从返回的response里得到新的Cookie,你可能得想办法把Cookie保存起来。
但是OkHttp可以不用我们管理Cookie,自动携带,保存和更新Cookie。
方法是在创建OkHttpClient设置管理Cookie的CookieJar

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) {
            cookieStore.put(httpUrl.host(), list);
        }

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

这样以后发送Request都不用管Cookie这个参数也不用去response获取新Cookie什么的了。还能通过cookieStore获取当前保存的Cookie。



 

服务器使用shiro做登录校验及权限验证的时候,app端访问时就要带上cookie,不然请求会提示未登录

private void postAsynHttp() {  
        mOkHttpClient=new OkHttpClient.Builder()  
                .cookieJar(new CookieJar() {  
                    private final HashMap<HttpUrl, List<Cookie>> cookieStore = new HashMap<>();  
  
                    @Override  
                    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {  
                        cookieStore.put(url, cookies);  
                        cookieStore.put(HttpUrl.parse("http://192.168.31.231:8080/shiro-2"), cookies);  
                        for(Cookie cookie:cookies){  
                            System.out.println("cookie Name:"+cookie.name());  
                            System.out.println("cookie Path:"+cookie.path());  
                        }  
                    }  
  
                    @Override  
                    public List<Cookie> loadForRequest(HttpUrl url) {  
                        List<Cookie> cookies = cookieStore.get(HttpUrl.parse("http://192.168.31.231:8080/shiro-2"));  
                        if(cookies==null){  
                            System.out.println("没加载到cookie");  
                        }  
                        return cookies != null ? cookies : new ArrayList<Cookie>();  
                    }  
                })  
                .build();  
        RequestBody formBody = new FormBody.Builder()  
                .add("username", "admin")  
                .add("password", "admin")  
                .build();  
        final Request request = new Request.Builder()  
                .url("http://192.168.31.231:8080/shiro-2/shiro-login")  
                .post(formBody)  
                .build();  
        Call call = mOkHttpClient.newCall(request);  
        call.enqueue(new Callback() {  
            @Override  
            public void onFailure(Call call, IOException e) {  
  
            }  
  
            @Override  
            public void onResponse(Call call, Response response) throws IOException {  
                String str = response.body().string();  
                Log.i("wangshu", str);  
  
                runOnUiThread(new Runnable() {  
                    @Override  
                    public void run() {  
                        showProgress(false);  
                        Toast.makeText(getApplicationContext(), "请求成功", Toast.LENGTH_SHORT).show();  
                    }  
                });  
            }  
  
        });  
    }  

 

posted on 2017-12-20 21:10  安卓笔记侠  阅读(37378)  评论(0编辑  收藏  举报