2012-05-24 89 views
7

這裏是目前簡單的描述我的應用程序。它使用一些使用標準HTTP會話的遠程服務器API。 登錄活動。它調用auth類,傳遞登錄名和密碼。如何在HttpContext中的活動之間保持HTTP會話cookie?

public class Auth extends AsyncTask{ 
... 
private DefaultHttpClient client = new DefaultHttpClient(); 
private HttpContext localContext = new BasicHttpContext(); 
private CookieStore cookieStore = new BasicCookieStore(); 
... 
public void auth(String login, String password) { 
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); 
    HttpPost request = new HttpPost(url); 
    ... 
} 
protected void onPostExecute(Boolean result){ 
    parent.loginresponse(result) 
} 

在成功的身份驗證,遠程服務器創建非標準HTTP會話,給我餅乾,保存在CookiStore。登錄後,loginresponse開始主要活動。我希望所有API請求都有一個通用類。

如何正確保持活動HTTP會話信息,在登錄後創建,在所有活動之間,並將其傳遞給相應的API方法所需的函數?

+0

最後,發現解決方案在http://stackoverflow.com/questions/4146861/android-httpclient-persistant-cookies和HTTP ://stackoverflow.com/questions/708012/android-how-to-declare-global-variables – uzer

回答

0

你可以做類似如下:

HttpClient client = getNewHttpClient(); 
     // 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); 
     try { 
      request = new HttpPost(url); 
      // request.addHeader("Accept-Encoding", "gzip"); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     if (postParameters != null && postParameters.isEmpty() == false) { 

      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
        postParameters.size()); 
      String k, v; 
      Iterator<String> itKeys = postParameters.keySet().iterator(); 
      while (itKeys.hasNext()) { 
       k = itKeys.next(); 
       v = postParameters.get(k); 
       nameValuePairs.add(new BasicNameValuePair(k, v)); 
      } 

      UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(
        nameValuePairs); 
      request.setEntity(urlEntity); 

     } 
     try { 

      Response = client.execute(request, localContext); 
      HttpEntity entity = Response.getEntity(); 
      int statusCode = Response.getStatusLine().getStatusCode(); 
      Log.i(TAG, "" + statusCode); 

      Log.i(TAG, "------------------------------------------------"); 

      if (entity != null) { 
       Log.i(TAG, 
         "Response content length:" + entity.getContentLength()); 

      } 
      List<Cookie> cookies = cookieStore.getCookies(); 
      for (int i = 0; i < cookies.size(); i++) { 
       Log.i(TAG, "Local cookie: " + cookies.get(i)); 

      } 

      try { 
       InputStream in = (InputStream) entity.getContent(); 
       // Header contentEncoding = 
       // Response.getFirstHeader("Content-Encoding"); 
       /* 
       * if (contentEncoding != null && 
       * contentEncoding.getValue().equalsIgnoreCase("gzip")) { in = 
       * new GZIPInputStream(in); } 
       */ 
       BufferedReader reader = new BufferedReader(
         new InputStreamReader(in)); 
       StringBuilder str = new StringBuilder(); 
       String line = null; 
       while ((line = reader.readLine()) != null) { 

        Log.i(TAG, "" + str.append(line + "\n")); 
       } 
       in.close(); 
       response = str.toString(); 
       Log.i(TAG, "response" + response); 
      } catch (IllegalStateException exc) { 

       exc.printStackTrace(); 
      } 

     } catch (Exception e) { 

      Log.e("log_tag", "Error in http connection " + response); 

     } finally { 
      // When HttpClient instance is no longer needed, 
      // shut down the connection manager to ensure 
      // immediate deallocation of all system resources 
      // client.getConnectionManager().shutdown(); 
     } 

     return response; 
    enter code here 
0

如果你使用像Dagger一個DI框架,就可以保持活動之間的HttpContext和你喜歡的地方注入了!

1

您可以使用一個單獨的類會是這個樣子:

public class UserSession 
{ 
    private static UserSession sUserSession; 

    private DefaultHttpClient client; 
    private HttpContext localContext; 
    private CookieStore cookieStore; 

    public DefaultHttpClient getClient() { 
     return client; 
    } 

    public void setClient(DefaultHttpClient client) { 
     this.client = client; 
    } 

    public HttpContext getLocalContext() { 
     return localContext; 
    } 

    public void setLocalContext(HttpContext localContext) { 
     this.localContext = localContext; 
    } 

    public CookieStore getCookieStore() { 
     return cookieStore; 
    } 

    public void setCookieStore(CookieStore cookieStore) { 
     this.cookieStore = cookieStore; 
    } 

    public get(){ 
     if (sUserSession == null) 
     { 
      sUserSession = new UserSession(); 
     } 
     return sUserSession; 
    } 
}