Andrews to get WebView cookie provided by the requesting Okhttp

Cookie is valid

Since the HTTP protocol is stateless, and server-side business must have a state. Cookie birth was originally designed to store state information in the web, to facilitate the use of the server. For example, to determine whether the user is the first visit to the site. The latest specification is RFC 6265, which is a server by the browser to work together to achieve the specification.
After the client requests the server, the server by carrying Cookie header Response, the client saved locally, the next time a request to carry the Cookie header in the client's request

A basic structure is as follows Cookie

Set-Cookie: "name = value ; domain = .domain.com; path = /; expires = Sat, 11 Jun 2016 11:29:42 GMT; HttpOnly; secure"
where name = value is mandatory, the other is available options. Cookie is mainly composed as follows:

name: the cookie name a uniquely determined. Generally cookie names are case-insensitive.

value: string value is stored in a cookie. Best be url encoded into the cookie name and value

Domain: the cookie domain for which it is effective. All requests are sent to the domain that contains cookie information. This value can contain subdomains (eg: yq.aliyun.com), may not include it (eg: .aliyun.com, valid for all the sub-domains of aliyun.com).

path: represent the cookie affect the path, with the browser would like to specify the path to send the cookie matching field based on the configuration.

expires: failure of the time, the time stamp (that is, when it should stop sending the cookie to the server) cookie when it should be deleted. If you do not set this timestamp, the browser will soon remove all the cookie when the page is turned off; but you can also set up their own time to delete. This value is in GMT format, if the client and server side inconsistent time deviations will use expires.

max-age: and expires the same effect, used to tell the browser how long the cookie expires (in seconds), rather than a fixed point in time. Normally, max-age is higher than the priority expires.

HttpOnly: tells the browser does not allow script to change this value by document.cookie, the same value is not visible in the document.cookie. But Zhang http request will still carry this cookie. Note that this value can not be obtained though in the script, but still exists in the form of a file in the browser installation directory. This setting is usually set on the server side.
secure: safety signs, after the specified only be sent to the server using SSL link when the link is http if it is not delivered this information. Even setting up secure property also does not mean that others can not see your machine locally stored cookie information, so do not put a cookie on important information to the server-side settings

How to get a cookie by intercepting http request

okhttp3 natural supports getting cookie
only need to implement CookieJar

//拦截cookie
    class LocalCookieJar implements CookieJar {
        List<Cookie> cookies;


        @Override
        public List<Cookie> loadForRequest(HttpUrl url) {
            if (cookies != null)
                return cookies;
            return new ArrayList<Cookie>();
        }

        @Override
        public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
            this.cookies = cookies;
          //存储当前cookie,用于webview中同步cookie
            CookiesManager.getInstance().cookieMap.put(url,cookies)
        }

    }

And add cooloeJar in the builder okhttp

OkHttpClient mOkHttpClient = OkHttpUtils.newInstance().connectTimeout(45, TimeUnit.SECONDS)
                .addInterceptor(new LogInterceptor())
                .cookieJar(new LocalCookieJar(cookieHashMap))//添加cookie管理
                .build();
Synchronization cookie in the webview

The following code in my project, effective pro-test, page setup may be different for different cookie parameters, required to pass cookie according to their own projects

webView.setWebViewClient(new CustomWebViewClient(mProgressWebView.getWebView()) {

            /**
             * 5.0以下
             */
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                synCookies(url);

                return super.shouldInterceptRequest(view, url);//将加好cookie的url传给父类继续执行
            }

            /**
            *5.0以上
            */
            @SuppressLint("NewApi")
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view , WebResourceRequest request) {
                String url = request.getUrl().toString();

                synCookies(url);
                return super.shouldInterceptRequest(view, url);
            }

        });

 public static void synCookies(String url){
  if ( !TextUtils.isEmpty(url) )  
            if (!null!=cookies ) {  
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){  
                    CookieSyncManager.createInstance( context);  
                }  
                CookieManager cookieManager = CookieManager.getInstance();  
                cookieManager.setAcceptCookie( true );  
                cookieManager.removeSessionCookie();// 移除  
                cookieManager.removeAllCookie();  
                for (Cookie cookie : cookies) {
                StringBuilder sbCookie = new StringBuilder();//创建一个拼接cookie的容器,
                sbCookie.append(cookie.name()+"="+cookie.value());
                sbCookie.append(";domain="+cookie.domain());
                sbCookie.append(";path="+cookie.path());
                String cookieValue = sbCookie.toString();  
                cookieManager.setCookie(url, cookieValue);//为url设置cookie 
             }
                CookieSyncManager.getInstance().sync();//同步cookie  
                String newCookie = cookieManager.getCookie(url);  //这里可以查看当前设置进去的cookie
            } 
    }

Guess you like

Origin blog.csdn.net/weixin_33817333/article/details/90825664