2012-12-10 55 views
1

我有兩個活動。Android HTTP GET登錄方法

主要活動運行應用程序並初始化http獲取請求代碼並將JSON響應解析爲字符串。

getmethod活動使用http get方法連接到服務器,並將響應發送回我的主要活動。

如何創建一個登錄方法,其中用戶手動輸入用戶名和密碼並將其傳遞給get方法?

+1

好了,你有什麼試過嗎? –

+0

重複:http://stackoverflow.com/questions/2959316/how-to-add-parameters-to-a-http-get-request-in-android – ben75

回答

1

您可以將此代碼添加到您的主要活動中 - 它將爲您完成所有繁重工作。

/** 
* Represents an asynchronous login/registration task used to authenticate 
* the user. 
*/ 
public class UserLoginTask extends AsyncTask<String, Void, Boolean> { 

    @Override 
    protected void onPostExecute(final Boolean success) { 
     if (success == true) { 
      //Do whatever your app does after login 

     } else { 
      //Let user know login has failed 
     } 
    } 

    @Override 
    protected Boolean doInBackground(String... login) { 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(
       "YOUR_ADDRESS_HERE.COM"); 
     String str = null; 
     String username = login[0]; 
     String password = login[1]; 

     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
     nameValuePairs.add(new BasicNameValuePair("username", username)); 
     nameValuePairs.add(new BasicNameValuePair("password", password)); 
     try { 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     } catch (UnsupportedEncodingException e1) { 
      e1.printStackTrace(); 
      return false; 
     } 

     try { 
      HttpResponse response = httpclient.execute(httppost); 
      str = EntityUtils.toString(response.getEntity()); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

        //Whatever parsing you need to do on the response 
        //This is an example if the webservice just passes back a String of "true or "false" 

     if (str.trim().equals("true")) { 

      return true; 
     } else { 
      return false; 

     } 
    } 

您可以創建該對象:(?也許放在一個onclick事件從一個登錄按鈕)

UserLoginTask mAuthTask = new UserLoginTask(); 

開始執行與請求:

mAuthTask.execute(mUsername, mPassword); 
+0

但對我來說,它不允許通過(字符串.. params)的方法,只有void的作品 –

+0

我不確定 - 那個重載(String ...)是指你傳遞每個單獨的字符串作爲參數,接收方法將它作爲一個數組的所有的您在方法調用中放入的字符串。你確定你是正確調用它嗎? – Hennaz

+0

謝謝你,我犯了一個錯誤,我沒有填寫適當的模板,我的一個是公共類UserLoginTask擴展AsyncTask 應該是公共類UserLoginTask擴展AsyncTask