okhttp3 with cookie request

Requests often carry cookies. As mentioned above, when creating a request, you can set parameters through the header. Cookie s are also one of the parameters. As follows:

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

You can then get a new Cookie from the returned response. You may have to find a way to save the Cookie.
But OkHttp can automatically carry, save and update cookies without us managing them.
The method is to set the Cookie jar of management Cookie in the creation of OkHttpClient

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

In this way, you don't need to worry about the Cookie parameter or response to get a new Cookie. The currently saved Cookie can also be obtained through the Cookie store.

 

When the server uses shiro for login verification and permission verification, the app side must bring cookie s when accessing, otherwise the request will prompt that it is not logged in

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("Not loaded to 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(), "Request succeeded", Toast.LENGTH_SHORT).show();  
                    }  
                });  
            }  
  
        });  
    }  

Tags: Android Shiro OkHttp

Posted on Mon, 04 May 2020 05:08:57 -0400 by Cesar