2013-05-13 44 views
6

如何退出HttpClient會話?退出HttpClient會話

我使用下面的代碼使用Apache的HttpClient

public HttpClient loginToHexgen(String username, String password) { 
     HttpClient client = new DefaultHttpClient(); 

     // send post url to login to hexgen 
     HttpPost post = new HttpPost("http://localhost:8080/j_spring_security_check"); 

     try { 
      // set the user name and password 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
      nameValuePairs.add(new BasicNameValuePair("j_username", username)); 
      nameValuePairs.add(new BasicNameValuePair("j_password", password)); 

      post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      HttpResponse response = client.execute(post); 

      HttpEntity entity = response.getEntity(); 

      if (entity != null) { 
       post.abort(); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return client; 
    } 

像下面登錄到應用程序:

HttpClient client = new DefaultHttpClient(); 
client= httpRequest.loginToHexgen("mayank", "hexgen"); 

這裏httpRequest是其中使用loginToHexgen方法的類。

如果我想用多個用戶以不同的用戶名和密碼登錄系統,該怎麼做?

例如在同一個會話中,我想註銷一個用戶並使用其他用戶登錄。

回答

4

您可以使用一種解決方法 - 使用新的cookieStore向新用戶發送請求。

// Create a local instance of cookie store 
cookieStore = new BasicCookieStore(); 
// Set the store 
httpClient.setCookieStore(cookieStore); 

服務器將爲您的新用戶開啓一個新的會話。請注意,舊會議將不會關閉。 我不建議使用這種方式。

會話管理在服務器端執行 - 您不能在客戶端執行。 我建議在測試結束時,您應該調用服務器URL來使服務器端的會話無效。 (通常使用表單身份驗證的應用程序具有註銷功能,您只需要使用它)

+1

+1對於答案,我試圖用不同的密碼發送不同的用戶,但令我驚訝的是它沒有產生任何問題,當我縮進時工作。感謝您的努力。 – 2013-05-13 07:45:48

+0

在'loginToHexgen'函數中有以下代碼的問題:'HttpClient client = new DefaultHttpClient();'。 它等於爲新用戶創建cookieStore。 注意事項:1.如果您想要代表經過身份驗證的用戶訪問URL,則需要使用相同的HttpClient實例(否則請求將沒有合唱)。 2.你可以檢查你的服務器,你會看到每個登錄一個新的會話被創建。 – Michael 2013-05-13 10:50:21