2014-02-28 275 views
0

我正在開發一個登錄服務,該登錄服務在登錄成功後登錄一個用戶,然後再次登錄一個新的腳本,並在登錄時給出一個cookie以獲取更多信息。這裏是我登錄後:使用cookie登錄後再次登錄

@Override 
     protected Boolean doInBackground(Void... params) { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://testsite.com/login"); 

      try { 
       List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
       nameValuePairs.add(new BasicNameValuePair("userid", "john")); 
       nameValuePairs.add(new BasicNameValuePair("password", "test")); 
       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

       HttpResponse response = httpclient.execute(httppost); 
       String TAG = "com.imtins.worryfree"; 
       String responseAsText = EntityUtils.toString(response.getEntity()); 

       Log.d(TAG, "Response from server: " + responseAsText.toString()); 

      } catch (ClientProtocolException e) { 

      } catch (IOException e) { 

      } 

從現在如果我使用相同的hpptClient不啓動新的一個,當我在另一個帖子它將使用我收到餅乾什麼香港專業教育學院讀?我在哪裏可以在我的示例中添加第二個帖子,或者它將如何顯示。剛開始使用android/Java,所以這對我來說有點困惑。

謝謝。

+0

同樣的方法中後httpclient.execute(httppost);你可以創建另一個httppost對象並再次激發httpclient.execute() – Gaurav

+0

@Gaurav你能告訴我看起來如何,我會接受它作爲答案 – BluGeni

回答

0

您可以使用HttpContext + CookieStore跟蹤請求之間的cookie狀態。我覺得這樣的事情會爲你工作(未經測試):

@Override 
    protected Boolean doInBackground(Void... params) { 
     HttpClient httpclient = new DefaultHttpClient(); 

     CookieStore cookieStore = new BasicCookieStore(); 
     HttpContext localContext = new BasicHttpContext(); 
     localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); 

     HttpPost httppost = new HttpPost("http://testsite.com/login"); 

     try { 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      nameValuePairs.add(new BasicNameValuePair("userid", "john")); 
      nameValuePairs.add(new BasicNameValuePair("password", "test")); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

      HttpResponse response = httpclient.execute(httppost, localContext); 
      String TAG = "com.imtins.worryfree"; 
      String responseAsText = EntityUtils.toString(response.getEntity()); 

      Log.d(TAG, "Response from server: " + responseAsText.toString()); 

     } catch (ClientProtocolException e) { 

     } catch (IOException e) { 

     } 

併爲您的第二個要求,重用localContext變量:

 // replace XXX below with correct URL 
     httppost = new HttpPost("http://testsite.com/XXXXXX"); 

     try { 
      // set entities here ... 

      HttpResponse response = httpclient.execute(httppost, localContext); 
      String TAG = "com.imtins.worryfree"; 
      String responseAsText = EntityUtils.toString(response.getEntity()); 

      Log.d(TAG, "Response from server: " + responseAsText.toString()); 

     } catch (ClientProtocolException e) { 

     } catch (IOException e) { 

     }