2012-05-24 8 views
7

Oto aktualny prosty opis mojej aplikacji. Używa jakiegoś zdalnego interfejsu API serwera, który używa standardowej sesji HTTP. Aktywność logowania. Wywołuje klasę uwierzytelniającą, przekazując login i hasło.Jak przechowywać pliki cookie sesji HTTP w HttpContext pomiędzy działaniami w systemie Android?

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

Po pomyślnym auth, zdalny serwer tworzy sesji HTTP Standart, wysyłając mi ciasteczko, zapisaną w CookiStore. Po zalogowaniu loginresponse rozpoczyna główną aktywność. Tam chcę mieć jedną uniwersalną klasę dla wszystkich żądań API.

Jak wykonać poprawne zachowanie informacji o sesji HTTP, utworzone po zalogowaniu, między wszystkimi działaniami i przekazanie jej do potrzebnych funkcji dla odpowiednich metod API?

+0

Wreszcie rozwiązania zostały znalezione w http://stackoverflow.com/questions/4146861/android-httpclient-persistant-cookies i http : //stackoverflow.com/questions/708012/android-how-to-declare-global-variables – uzer

Odpowiedz

0

można zrobić coś jak poniżej:

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

Jeśli używasz ramy DI jak Dagger, można utrzymać HttpContext między działaniami i wstrzyknąć go gdziekolwiek chcesz!

1

Można użyć klasy singleton, że będzie wyglądać mniej więcej tak:

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; 
    } 
} 
Powiązane problemy