Android混合开发不管是使用的哪种hybird框架都是基于WebView实现的,所以我们需要在原生页面拿到服务器返回的cookies的时候将其同步到WebView中,同时在原生页面调用服务器api之前,从WebView_cookies.db中拿到最新的cookies写入http请求头当中,只有这样才能保持用户的登录状态,否则服务器检测到cookies中的sessionId过期后会返回错误码提示用户登录失效。以okhttp网络框架为例,通过写两个拦截器分别在发送http请求的时候获取本地cookies写到http header当中,在接收http响应的时候从响应头中拿到最新的cookies并刷新本地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()); Listcookies = 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; }}复制代码