出於某種原因,這個工作:我改變了URL從HTTPS初始cookie的請求HTTP,然後又改了回來。
但最後我決定改變我的實現,並與loopj去爲阿利斯泰爾建議。結果是更加優雅。這是我的登錄活動(請注意,我的客戶端連接到由循環J API給予永久性Cookie存儲):
public class AccountList extends ListActivity {
protected AccountManager accountManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
accountManager = AccountManager.get(getApplicationContext());
Account[] accounts = accountManager.getAccountsByType("com.google");
this.setListAdapter(new ArrayAdapter<Account>(this, R.layout.list_item, accounts));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Account account = (Account)getListView().getItemAtPosition(position);
accountManager.invalidateAuthToken("com.google", null);
accountManager.getAuthToken(account, "ah", null, this, new GetAuthTokenCallback(), null);
}
private class GetAuthTokenCallback implements AccountManagerCallback<Bundle> {
public void run(AccountManagerFuture<Bundle> result) {
AsyncHttpClient client = new AsyncHttpClient();
PersistentCookieStore myCookieStore = new PersistentCookieStore(getBaseContext());
client.setCookieStore(myCookieStore);
try {
Bundle bundle;
bundle = result.getResult();
Intent intent = (Intent)bundle.get(AccountManager.KEY_INTENT);
if(intent != null) {
// User input required
startActivity(intent);
} else {
String token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
String url = "http://myapp.appspot.com/_ah/login?continue=http://localhost/&auth=" + token;
client.post(url, new AsyncHttpResponseHandler());
Intent backToMainActivity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(backToMainActivity);
}
} catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
由於循環J給出了持久性cookie存儲,都讓我有另一項活動做的是初始化一個客戶端並將其連接到持久cookie存儲。這爲新客戶提供了我從登錄活動中獲得的所有Cookie。初始化看起來是這樣的:
AsyncHttpClient client = new AsyncHttpClient();
client.setCookieStore(new PersistentCookieStore(this));
BTW & FYI:該循環J庫使用SharedPreferences
API,以存儲的cookie,並很好地將其包裝爲PersistentCookieStore
。
來源
2012-12-23 11:28:57
Uri
所以我的答案是正確的? – alistair
是的,它指出我到了正確的位置,這就是爲什麼我upvoted,只是缺乏一點解釋。 – Uri