I’ve never used AsyncHttp to save sessions before, but I have to use it today! Interface design is limited, SO I have to use a special interface for the browser, this time I will encapsulate AsyncHttpClient as a singleton, through this way to save the Session, so for the time being, until I find another solution to update this article!

A, encapsulation

Start by encapsulating a utility class that deals specifically with cookies:

public class CookieUtils { private static List<Cookie> cookies; Public static List<Cookie> getCookies() {return cookies! = null ? cookies : new ArrayList<>(); } public static void setCookies(List<Cookie> cookies) {cookieutils.cookies = cookies; } public static void saveCookie(AsyncHttpClient); Context context) { PersistentCookieStore cookieStore = new PersistentCookieStore(context); client.setCookieStore(cookieStore); PersistentCookieStore = new; PersistentCookieStore = new; PersistentCookieStore = new PersistentCookieStore(context); List<Cookie> cookies = cookieStore.getCookies(); return cookies; PersistentCookieStore = new public static void clearCookie(Context Context) {PersistentCookieStore = new PersistentCookieStore(context); cookieStore.clear(); }}Copy the code

Encapsulate AsyncHttpClient so that all asynchttPClients use the same object!

public class FinalAsyncHttpClient { private AsyncHttpClient client; /* Constructor */ public FinalAsyncHttpClient() {client = new AsyncHttpClient(); // Instantiate client client.setTimeout(5); If (cookieutils.getcookies ()! = null) { BasicCookieStore bcs = new BasicCookieStore(); bcs.addCookies(CookieUtils.getCookies().toArray( new Cookie[CookieUtils.getCookies().size()])); // Get the cookie list client.setCookiestore (BCS); Public AsyncHttpClient getAsyncHttpClient() {return this.client; }}Copy the code

Second, the use of

Gets the object and sets the save Cookie

AsyncHttpClient asyncHttpClient = new FinalAsyncHttpClient().getAsyncHttpClient();
CookieUtils.saveCookie(asyncHttpClient,LoginAty.this);
Copy the code

Login successful

asyncHttpClient.post(AppConfig.loginAddress, params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { //.... Xtoast.success (getContext(), "login succeeded ").show(); CookieUtils.setCookies(CookieUtils.getCookie(LoginAty.this)); / /... }Copy the code

Third, expand

However, there is also a problem with this, the cookie will disappear every time we open the App, we just save the cookie through the way of serialization, if we find that the cookie expires, now there is a better solution, directly update the cookie when the App is opened!