问题描述
更新:不应再向阅读本文的任何人推荐此问题及其答案.Android 不再推荐 HttpClient(阅读:已弃用),而是推荐HttpUrlConnection.现在使用的库的一个很好的例子是 Retrofit 和 OkHttp.在这个问题的上下文中,cookie 可以保存、存储和交付与后续查询.这不是透明处理的.使用 OkHttp,您可以使用拦截器.
UPDATE: This question and its answers should no longer be recommended to anyone reading this. Android no-longer recommends HttpClient (read: deprecated), and instead recommends HttpUrlConnection. A good example of libraries to use now, are Retrofit and OkHttp. In the context of this question, cookies can be saved, stored and delivered with subsequent queries. This is not handled transparently. With OkHttp you can use Interceptors.
我有一个具有多个意图的 Android 应用程序.
I have an Android application with multiple intents.
第一个意图是登录表单,后续意图依赖于登录过程提供的 cookie.
The first intent is a login form, subsequent intents rely on cookies provided from the login process.
我遇到的问题是 cookie 似乎没有在意图中持续存在.我正在每个意图中创建新的 HttpClient(我最初尝试将 Parcelable 传输到每个意图,但效果不佳).
The problem that I am having is that cookies do not appear to be persisting across the intents. I am creating new HttpClients in each intent (I initially tried to Parcelable transmit it across to each intent, which did not work so well).
有没有人有任何让 cookie 跨意图持久化的技巧?
Does anyone have any tips for making cookies persist across intents?
推荐答案
您可以按照@Emmanuel 的建议进行操作,也可以通过 BasicHttpContext.
You can do what @Emmanuel suggested or you can pass the BasicHttpContext between the HttpClients you are creating.
使用上下文和 cookie 的示例,完整代码在这里
Example Use of context and cookies, complete code here
HttpClient httpclient = new DefaultHttpClient();
// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet httpget = new HttpGet("http://www.google.com/", localContext);
这篇关于Android HttpClient 持久性 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!