2013-03-27 56 views
1

當我聲明一個cookie存儲時,我在應用程序中修復了崩潰和錯誤,但它不保存cookie或其他位置出錯。請求不使用保存的Cookie在PersistentCookieStore

起初,我把這些2線:

AsyncHttpClient client = new AsyncHttpClient(); 
PersistentCookieStore myCookieStore; 

然後,我有一個POST:

public void postRequestLogin(String url, RequestParams params) { 
    myCookieStore = new PersistentCookieStore(this); 
    client.post(url, params, new AsyncHttpResponseHandler() { 
     @Override 
     public void onSuccess(String response) { 
      client.setCookieStore(myCookieStore); 
      System.out.println(response); 

      if(response.contains("Login successful!")) { 
       TextView lblStatus = (TextView)findViewById(R.id.lblStatus); 
       lblStatus.setText("Login successful!"); 
       getRequest("url"); 
      } else { 
       TextView lblStatus = (TextView)findViewById(R.id.lblStatus); 
       lblStatus.setText("Login failed!"); 
       TextView source = (TextView)findViewById(R.id.response_request); 
       source.setText(response); 
      } 
     } 
    }); 

} 

那麼就應該保存Logincookies和使用它的GET請求:

public void getRequest(String url) { 
    myCookieStore = new PersistentCookieStore(this); 
    client.get(url, new AsyncHttpResponseHandler() { 
     @Override 
     public void onSuccess(String response) { 
      client.setCookieStore(myCookieStore); 
      System.out.println(response); 
      TextView responseview = (TextView) findViewById(R.id.response_request); 
      responseview.setText(response); 
     } 
    }); 
} 

但它不使用cookies。當我執行GET請求時,我已經註銷。

編輯:我忘了說,我用一個lib從本教程:http://loopj.com/android-async-http/

+0

讓您的標題具體化非常重要,因爲這會讓知道如何提供幫助的人更容易看到您的問題。您不需要使用「Android」或「Java」等詞語,因爲問題已經有了標籤。 – 2013-03-27 19:58:17

回答

2

我認爲這個問題是您設置的cookie存儲後請求已經完成(在onSuccess方法)。嘗試在提出請求之前設置它:

myCookieStore = new PersistentCookieStore(this); 
client.setCookieStore(myCookieStore); 
client.post(url, params, new AsyncHttpResponseHandler() { 

您還正在爲每個請求創建一個新的cookie存儲。如果你做了多個請求會發生什麼?它將創建一個新的cookie存儲並使用它(並且新的cookie存儲不會有您的cookie)。嘗試將這部分代碼移動到您的構造函數中:

myCookieStore = new PersistentCookieStore(this); 
client.setCookieStore(myCookieStore); 

然後將其從其他函數中移除。

+0

@Phil此外,我只是再次查看您的代碼,並且您正在爲每個請求創建一個新的Cookie存儲。您應該只調用一次新的PersistentCookieStore()和setCookieStore(可能在構造函數中)。 – 2013-03-27 20:06:52

+0

好吧,我現在只是在構造函數中,做得很好,再次感謝 – Phil 2013-03-27 20:11:41