出于某种原因,这行得通:我将初始 cookie 请求的 URL 从 https 更改为 http,然后将其更改回来。
但最后我决定改变我的实现,并按照alistair的建议使用 loopj。结果要优雅得多。这是我的登录活动(请注意,我正在将客户端连接到 loopj 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();
}
}
}
}
因为 loopj 提供了持久 cookie 存储,所以我在另一个活动中所要做的就是初始化一个客户端并将其与持久 cookie 存储连接。这为新客户端提供了我从登录活动中获得的所有 cookie。初始化看起来像这样:
AsyncHttpClient client = new AsyncHttpClient();
client.setCookieStore(new PersistentCookieStore(this));
BTW & FYI:loopj 库使用SharedPreferences
API 来存储 cookie,并将其很好地包装为PersistentCookieStore
.