【问题标题】:How to maintain session in android using an HttpClient如何使用 HttpClient 在 android 中维护会话
【发布时间】:2014-05-19 17:00:57
【问题描述】:

我正在使用HttpClient 进行服务器连接,如下所示:

DefaultHttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com/login");
HttpResponse response = client.execute(httppost);

服务器会话使用 cookies

为了保持会话,我必须为所有后续连接使用相同的客户端。我正在做并且工作正常。

但问题是,在 android 中,Activity 数据通常会在需要时被销毁,这也会破坏 HttpClient(当我的应用程序在 baclground 中时),因此会话正在丢失。

有没有办法让HttpClient 持久化?或者我该如何解决这种情况?

谢谢。

【问题讨论】:

    标签: android session


    【解决方案1】:

    据我所知,无法保存您的会话并在 Activity 重新启动后重新创建。

    唯一的一种方法是将您的HttpClient 代码放入服务中。通过这种方式,您可以玩活动,而不必担心会话中断。

    你可以找到Services文档here

    服务器会话使用 cookie。

    默认情况下,Android cookie 已启用,您无需担心。

    当然,您可以存储 Cookie,但我看不出它可以以某种方式帮助您解决问题的原因。

    无论如何,这是一种获取 Cookie 的技术:

    List<Cookie> mCookies = null;
    
    mCookies = httpclient.getCookieStore().getCookies();
    
            if (mCookies.isEmpty()) {
                Log.d("test_runner", "Cookies: None");
            } else {
                for (int i = 0; i < mCookies.size(); i++) {
                    System.out.println("- " + mCookies.get(i).toString());
                    Log.d("test_runner", "Cookies: [" + i + "]" + mCookies.get(i).toString());
                }
            }
    

    这是一种将它们放回去的方法:

     CookieStore cookieStore = new BasicCookieStore(); 
    
         for(Cookie cook : mCookies){
             cookieStore.addCookie(cook); 
         }
    
         httpclient = new DefaultHttpClient(params);
         httpclient.setCookieStore(cookieStore);
    

    【讨论】:

      【解决方案2】:

      最好的办法是将服务器执行的所有功能放在唯一的类中,该类将由要连接的任务调用。我称这个类为 WebServiceManager。这个类的方法和服务端完全一样。

      你想要一个独特的会话:

      private static WebServiceManager wsm = null;
      
      public static WebServiceManager getInstance() {
          if (wsm == null) {
              wsm = new WebServiceManager();
          }
          return wsm;
      }
      
      private final HttpClient httpClient;
      
      private WebServiceManager() {
          httpClient=new DefaultHttpClient();
      }
      

      然后您调用 webServiceManager 实例的方法以始终使用相同的 httpclient 并保留您的 cookie。 :)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-28
        • 1970-01-01
        • 2014-10-27
        • 2011-03-03
        • 2013-08-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多