简体   繁体   English

Android HttpClient持久性cookie

[英]Android HttpClient persistent cookies

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 . Android不再推荐使用HttpClient(读取:弃用),而是推荐使用HttpUrlConnection A good example of libraries to use now, are Retrofit and OkHttp . 现在使用的库的一个很好的例子是RetrofitOkHttp In the context of this question, cookies can be saved, stored and delivered with subsequent queries. 在此问题的上下文中,可以使用后续查询保存,存储和传递cookie。 This is not handled transparently. 这不是透明处理的。 With OkHttp you can use Interceptors . 使用OkHttp,您可以使用拦截器

I have an Android application with multiple intents. 我有一个具有多个意图的Android应用程序。

The first intent is a login form, subsequent intents rely on cookies provided from the login process. 第一个意图是登录表单,后续意图依赖于登录过程提供的cookie。

The problem that I am having is that cookies do not appear to be persisting across the intents. 我遇到的问题是,cookie似乎并没有贯穿整个意图。 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). 我在每个意图中创建新的HttpClients(我最初尝试将Parcelable传输到每个意图,但效果不是很好)。

Does anyone have any tips for making cookies persist across intents? 有没有人有任何提示让饼干坚持意图?

You can do what @Emmanuel suggested or you can pass the BasicHttpContext between the HttpClients you are creating. 您可以执行@Emmanuel建议的操作,也可以在要创建的HttpClient之间传递BasicHttpContext

Example Use of context and cookies, complete code here 示例使用上下文和cookie, 在此处完成代码

    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);

Don't create new HttpClients; 不要创建新的HttpClients; this will clear the cookies. 这将清除cookie。 Reuse a single HttpClient. 重用一个HttpClient。

define HttpClient in Application class, and use it in activity. 在Application类中定义HttpClient,并在activity中使用它。

in Application 在申请中

public class AAA extends Application {
    public HttpClient httpClient; 

    httpClient = new DefaultHttpClient(); 

in Activity 在活动中

AAA aaa = (AAA)getApplication();
httpClient = app.httpClient;

使您的httpClient成为单例类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM