Cookies management under Android mixed-use development mode

Android mixed-use development Whatever the hybird framework is based on the use of WebView to achieve, so we need to get the cookies returned by the server in the native page when it is synchronized to the WebView while before the original page calls the server api, from WebView_cookies .db write in to get the latest cookies http request header, only way to maintain the user's login status, otherwise the server will return the cookies detected in sessionId expired error code prompt the user to log failure. To okhttp network framework, for example, obtained by writing two interceptors were when sending http request http header among local writes cookies, cookies get the latest from the response header when it receives a response and refresh the local http cookies:

public class AddCookieInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        final Context context = PApplication.getInstance();
        String cookies = Commons.getSSOCookie(context);
        Request.Builder builder = chain.request().newBuilder();
        if (EmptyHelper.isNotEmptyOrNotNull(cookies)) {
            Request newRequest = builder.addHeader("Cookie", cookies).build();
            return chain.proceed(newRequest);
        }
    }
}
复制代码
public class ReceivedCookieInterceptor implements Interceptor{

    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());
        List<String> cookies = originalResponse.headers("Set-Cookie");
        if (!cookies.isEmpty()) {
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);// 允许接受 Cookie
            String domain = HeadDomin();
            for(String cookie : cookies){
                cookieManager.setCookie(domain,cookie);
            }
            cookieManager.flush();
        }
        return originalResponse;
    }
}
复制代码

Reproduced in: https: //juejin.im/post/5ce79a4f6fb9a07ee4633d9d

Guess you like

Origin blog.csdn.net/weixin_33721427/article/details/91465160