2013-07-10 157 views
1

我在这个网站上阅读了几个topis如何保持会话活着,并按照建议,但我的客户连续失去与服务器的连接。 与erver完成JSONParser类的通信,JSONParser从UILApplication获取HttpClient,如果Internet连接被丢弃,它将设置并恢复Cookie。不幸的是,这不起作用。请帮我解决这个问题。为什么Cookie会话保持死亡

UILApplication

public class UILApplication extends Application { 
private static Object mLock = new Object(); 
    private static CookieStore mCookie = null; 
public static HttpClient getHttpClient() { 
     final DefaultHttpClient httpClient = HttpClientFactory 
       .getThreadSafeClient(); 
     synchronized (mLock) { 
      if (mCookie == null) { 
       mCookie = httpClient.getCookieStore(); 
      } else { 
       httpClient.setCookieStore(mCookie); 
      } 

     } 
     List<Cookie> cookies = mCookie.getCookies(); 
     if (cookies.isEmpty()) { 
      Log.d("COOK", "none"); 
     } else { 
      for (int i = 0; i < cookies.size(); i++) { 
       Log.d("COOK", "- " + cookies.get(i).toString()); 
      } 
     } 
     return httpClient; 
    } 

HttpClientFactory

public class HttpClientFactory { 
    private static DefaultHttpClient client=null; 
// private static CookieStore mCookie = null; 


    public boolean isNetworkConnected(Context context) { 
     ConnectivityManager conMgr = (ConnectivityManager) context 
       .getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo i = conMgr.getActiveNetworkInfo(); 
     if (i == null) { 
      return false; 
     } 
     if (!i.isConnected()) { 
      return false; 
     } 
     if (!i.isAvailable()) { 
      return false; 
     } 
     return true; 
    } 

    public synchronized static DefaultHttpClient getThreadSafeClient() { 

     if (client != null) { 
      Log.d("HTTPCLIEN", "REUSE"); 

      // return client; 
     } else { 
      Log.d("HTTPCLIEN", "new"); 
      client = new DefaultHttpClient(); 

      ClientConnectionManager mgr = client.getConnectionManager(); 

      HttpParams params = client.getParams(); 
      HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 
      HttpProtocolParams.setHttpElementCharset(params, HTTP.UTF_8); 

      client = new DefaultHttpClient(new ThreadSafeClientConnManager(
        params, mgr.getSchemeRegistry()), params); 


      // return client; 
     } 
//  synchronized (mLock) { 

     return client; 
    } 

    public synchronized static DefaultHttpClient killSession() { 

     client = new DefaultHttpClient(); 

     ClientConnectionManager mgr = client.getConnectionManager(); 

     HttpParams params = client.getParams(); 
     client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, 
       mgr.getSchemeRegistry()), params); 
//  
     return client; 

    } 
} 

JSONParser

public class JSONParser { 
    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) { 

     if (isOnline()) { 
      try { 

       String u = url; 
       u = u + "?"; 

       httpClient = UILApplication.getHttpClient(); 

       HttpPost httpPost = new HttpPost(url); 
       httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); 
       for (int i = 0; i < params.size(); i++) { 
        u = u + params.get(i).getName() + "=" 
          + params.get(i).getValue() + "&"; 
       } 
       Log.d("your url is", u); 
       HttpResponse httpResponse = httpClient.execute(httpPost); 
       List<Cookie> cookies = ((AbstractHttpClient) httpClient).getCookieStore().getCookies(); 
       UILApplication.setCoockies(((AbstractHttpClient) httpClient).getCookieStore()); 
       if (cookies.isEmpty()) { 
        System.out.println("None"); 
       } else { 
        for (int i = 0; i < cookies.size(); i++) { 

         System.out.println("- " + cookies.get(i).toString()); 
        } 
       } 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 
       Log.d("data is sent", "true"); 

      } catch (UnsupportedEncodingException e) { 
       e.printStackTrace(); 
       return null; 
      } catch (ClientProtocolException e) { 
       e.printStackTrace(); 
       return null; 
      } catch (IOException e) { 
       e.printStackTrace(); 
       return null; 

      } 
      Log.d("wait", "true"); 
      try { 

       BufferedReader reader = new BufferedReader(
         new InputStreamReader(is, "UTF-8"), 8); 
       StringBuilder sb = new StringBuilder(); 
       String line = null; 
       while ((line = reader.readLine()) != null) { 

        sb.append(line + "\n"); 
       } 
       is.close(); 
       json = sb.toString(); 
       if (json.contains("error:2")) { 
        return null; 
       } 
       Log.d("JSON", json); 
      } catch (Exception e) { 
       Log.e("Buffer Error", "Error converting result " + e.toString()); 
       return null; 
      } 
      // try parse the string to a JSON object 
      try { 
       jObj = new JSONObject(json); 
      } catch (JSONException e) { 
       Log.e("JSON Parser", "Error parsing data " + e.toString()); 
       return null; 
      } 
      // dialog.dismissDialog(); 
      // pd.dismiss(); 
      return jObj; 
     } 
     // pd.dismiss(); 
     // dialog.dismissDialog(); 

//  error(); 
     return null; 

    } 
} 

编辑:它看起来像mCookie由GC一段时间后erised,偏偏这个heppens如果是一个应用程序cla的静态字段SS?

+0

也许cookie的超时时间太短。如果你使用的是CTRL + SHIFT + I - > Resources(tab) - > Cookies并检查cookie的超时时间。也许这不是你的问题。 “ –

+0

”静态变量不能在加载类时进行垃圾回收,它们可以在相应的类加载器(负责加载此类的垃圾回收器)本身收集以进行垃圾回收时收集。“ –

+0

看起来mCookie在一段时间之后被GC诅咒了,但为什么如果这是应用程序类的静态字段呢? “你用saveInstance说它吗?” –

回答

0

我会使用HttpURLConnection那是recommended

您就可以启用VM级cookie管理是这样的:那么

CookieHandler.setDefault(new CookieManager()); 

Cookies是只存储在内存中,但你可以实现自己的CookieStore如果你想。

您可以阅读更多关于cookies和HttpURLConnectionhere

1

听起来好像你从服务器上取回的cookie是一个session cookie,简单起来就意味着当你停止应用程序并再次运行它时,cookie会被丢弃。

我会建议在服务器端设置一个Max-Age or an Expire的cookie。这应该可以解决问题。

调试此类问题的另一种方法是打印出您从服务器获得的HTTP头。实际上可能有一个错误,它没有正确设置cookie过期或Max-Age。

另一个非常重要的事情是设置cookie的Secure属性,如果您使用它来验证HTTP客户端/请求,否则您的cookie将在每次执行HTTP请求时发送到在cookie,尽管该请求是关于为同一个域下载图像的。这样,如果攻击者嗅探到网络流量可以劫持用户会话。