Whatever Hybird framework is used for Android hybrid development is based on WebView, so we need to synchronize the cookies returned by the server to the WebView when the native page gets them, and before the native page calls the server API, Get the latest cookies from WebView_cookies. Db and write them into the HTTP request header. Only in this way can the user’s login state be maintained. Take okHTTP network framework as an example, by writing two interceptors to obtain local cookies when sending HTTP requests and write them into HTTP headers, and get the latest cookies from the response headers and refresh local cookies when receiving HTTP responses:
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();
returnchain.proceed(newRequest); }}}Copy the code
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); // Allow Cookie String domain = HeadDomin();for(String cookie : cookies){
cookieManager.setCookie(domain,cookie);
}
cookieManager.flush();
}
returnoriginalResponse; }}Copy the code