zoukankan      html  css  js  c++  java
  • 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();  
                        }  
                    });  
                }  
      
            });  
        }  
  • 相关阅读:
    uWSGI 是一種協議,同時它也是一個程式。
    影像数据的裁切和保存
    Android Studio、IDEA 获取开发版SHA1值和发布版SHA1值,详细过程
    Android Studio的Signature Versions选择,分别是什么意思
    Android Studio更改项目SDK的版本
    c#+ArcGIS Engine-获取矢量图层的空间参考
    64。node.js 中间件express-session使用详解
    63.note.js之 Mongodb在Nodejs上的配置及session会话机制的实现
    62.nodejs中的ejs模板学习
    61.node.js开发错误——Error: Connection strategy not found
  • 原文地址:https://www.cnblogs.com/ganchuanpu/p/8075859.html
Copyright © 2011-2022 走看看