0

我希望用户通过 HttpGet/HttpPost 操作执行不同的任务。我想保存 Cookie,以便用户只需要在 cookie 到期后登录。

在浏览互联网时,我看到“PersistentCookiestore”是一个很好的起点。

问题一:如何在HttpClient软件中使用(apache)PersistentCookieStore?我没有看到完整的示例,例如如何在第一次使用 httpclient 时开始使用 PersistentCookieStore。

参见例如:

static PersistentCookieStore cookie_jar = new PersistentCookieStore( getApplicationContext()); 

public void login() { 
    // how to connect the persistent cookie store to the HttpClient? 
    ....
    client2 = new DefaultHttpClient( httpParameters);
    …
    client2.setCookieStore(cookie_jar);
    ....
    HttpGet method2 = new HttpGet(uri2);
    ....
    try {
     res = client2.execute(method2); 
}
catch ( ClientProtocolException e1) { e1.printStackTrace(); return false; }
    ....

问题 2:如何在通话后更新 cookie,或者这永远不需要?换句话说:当我在调用 client2.execute(...) 后调用 HttpGet 或 HttpPost 后必须更新 cookie 时。

在带有 httpclient 的(非持久性)cookie 的示例代码中,我看到:

cookie_jar = client.getCookieStore(); 
….
HttpGet or HttpPost … 
client.setCookieStore( ....) 
client.execute( .. )  // second call

谢谢你的帮忙。

4

2 回答 2

0

问题 1:我将 AsyncHttpClient 与 PersistenCookieStore 一起使用

问题 2:我仅在用户登录应用程序时更新我的​​ cookie

AsyncHttpClient client = new AsyncHttpClient();
PersistentCookieStore myCookie = new PersistentCookieStore(CONTEXT);


//Clean cookies when LOGIN
if(IS_LOGIN)
    myCookie.clear();

client.setCookieStore(myCookie);

现在我想知道如何知道cookie何时过期

于 2014-11-03T14:49:00.067 回答
0

最初的问题是:应用启动后如何防止每次登录?答案当然是使用cookies。那么如何存储 cookie 以便在应用重启后可以重复使用?

对我有用的答案非常简单:只需将 cookiestore 转换为字符串,在退出应用程序之前将其放入共享首选项中。在下一个应用程序启动后,因此在下一次登录之前,只需从共享首选项中获取刺痛,将其转换回 cookiestore。使用 cookiestore 会阻止我再次登录。

public void saveCookieStore( CookieStore cookieStore) {
    StringBuilder cookies = new StringBuilder();
    for (final Cookie cookie : cookieStore.getCookies()) {
        cookies.append(cookie.getName());
        cookies.append('=');
        cookies.append(cookie.getValue());
        cookies.append('=');
        cookies.append(cookie.getDomain());
        cookies.append(';');
    }
    SharedPreferences.Editor edit = sharedPref.edit();
    edit.putString( MY_GC_COOKIESTORE, cookies.toString());
    edit.commit();
}

// retrieve the saved cookiestore from the shared pref
public CookieStore restoreCookieStore() {
    String savedCookieString = sharedPref.getString( MY_GC_COOKIESTORE, null);
    if( savedCookieString == null || savedCookieString.isEmpty()) { 
        return null; 
    }
    CookieStore cookieStore = new BasicCookieStore();
    for ( String cookie : StringUtils.split( savedCookieString, ';')) {
        String[] split = StringUtils.split( cookie, "=", 3);
        if( split.length == 3) {
            BasicClientCookie newCookie = new BasicClientCookie( split[0], split[1]);
            newCookie.setDomain( split[2]);
            cookieStore.addCookie( newCookie);
        }
    }
    return cookieStore;
}
于 2014-12-22T07:59:05.950 回答