廣告

2014年11月29日 星期六

[Android 與 webService溝通,使用 POST and GET][post and get]

這邊使用登入系統為範例,使用 post and get 方法,

  • POST:將資料用namevaluepair的方式送出。
  • GET  :將資料加在網址後面送出。


下列範例搭配AsyncTask實作。

AsyncTask:不影響main UI介面獨立執行緒,通常在doInBackground()做事情,

做完後會跑onPostExecute(),在這邊做一些做完的動作(關dialog等等)。



public class Lewis extends Activity {

 public static final int DIALOG_LOGIN_PROGRESS = 2;
 private ProgressDialog mpDialog = null;
 private EditText user, password;
 private Button login;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main2);
  context = this;

  user = (EditText) findViewById(R.id.editText1);
  password = (EditText) findViewById(R.id.editText2);
  login = (Button) findViewById(R.id.login);
  login.setOnClickListener(loginoOnClickListener);

 }

 @Override
 protected Dialog onCreateDialog(int id) {
  switch (id) {

  case DIALOG_LOGIN_PROGRESS:
   mpDialog = new ProgressDialog(Lewis.this);
   mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
   mpDialog.setTitle("登入中");
   mpDialog.setMessage("wait");
   mpDialog.setIndeterminate(false);
   mpDialog.setCancelable(false);
   mpDialog.setProgress(0);
   mpDialog.incrementProgressBy(1);
   mpDialog.show();
   return mpDialog;

  default: {
   return null;
  }

  }
 }

 private Button.OnClickListener loginoOnClickListener = new Button.OnClickListener() {

  public void onClick(View arg0) {
   showDialog(DIALOG_LOGIN_PROGRESS);
   
   //GET方法
   UserLoginTask_GET mAuthTask = new UserLoginTask_GET();
   mAuthTask.execute(user.getText().toString().trim(), password
     .getText().toString().trim());
   
   //POST方法
   UserLoginTask_POST mAuthTask = new UserLoginTask_POST();
   mAuthTask.execute(user.getText().toString().trim(), password
     .getText().toString().trim());
   
  }

 };

 public class UserLoginTask_GET extends AsyncTask> {

  @Override
  protected void onPostExecute(final ArrayList status_result) {

   mpDialog.cancel();

   if (status_result.get(0).equals("yes")) {

    // 帳密正確且登入完成後這邊做你要做的事情。
   } else {
    AlertDialog.Builder delAlertDialog = new AlertDialog.Builder(
      Lewis.this);
    delAlertDialog.setTitle("帳號密碼錯誤");

    // 自定義dialog的位置
    Window window = delAlertDialog.show().getWindow();
    WindowManager.LayoutParams lp = window.getAttributes();
    lp.alpha = 0.6f;
    lp.width = 300;
    window.setGravity(Gravity.CENTER); // window.setGravity(Gravity.BOTTOM);
    window.setAttributes(lp);

    user.setText("");
    password.setText("");
   }

  }

  @Override
  protected ArrayList doInBackground(String... login) {
   HttpClient client = new DefaultHttpClient();
   String url = "your webservice url";
   HttpGet get = new HttpGet(url + "?" + "username=" + login[0] + "&"
     + "password=" + login[1] + "&" + "project_type=lewis");
   String result = null;
   ArrayList statusResult = new ArrayList();
   statusResult.add("no");
   Log.e("login[0]", login[0] + "---" + login[1]);
   try {
    HttpResponse response = client.execute(get);
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
     HttpEntity resEntity = response.getEntity();
     if (resEntity != null) {
      result = EntityUtils.toString(resEntity, HTTP.UTF_8);
      statusResult.set(0, "yes");// 代表帳密正確(經由你的webservice判斷)
     }
    } else {
     HttpEntity resEntity = response.getEntity();
     if (resEntity != null) {
      result = EntityUtils.toString(resEntity, HTTP.UTF_8);
      statusResult.set(0, "no");
     }
    }
   } catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   statusResult.add(result);
   if (statusResult.get(0).equals("yes")) {
    return statusResult;
   } else {
    return statusResult;
   }
  }
 }
 
 
 
 
 public class UserLoginTask_POST extends AsyncTask> {

  @Override
  protected void onPostExecute(final ArrayList status_result) {

   mpDialog.cancel();

   if (status_result.get(0).equals("yes")) {

    // 帳密正確且登入完成後這邊做你要做的事情。
   } else {
    AlertDialog.Builder delAlertDialog = new AlertDialog.Builder(
      Lewis.this);
    delAlertDialog.setTitle("帳號密碼錯誤");

    // 自定義dialog的位置
    Window window = delAlertDialog.show().getWindow();
    WindowManager.LayoutParams lp = window.getAttributes();
    lp.alpha = 0.6f;
    lp.width = 300;
    window.setGravity(Gravity.CENTER); // window.setGravity(Gravity.BOTTOM);
    window.setAttributes(lp);

    user.setText("");
    password.setText("");
   }

  }

  @Override
  protected ArrayList doInBackground(String... login) {
   HttpClient httpclient = new DefaultHttpClient();
   HttpPost httppost = new HttpPost("your webservice url");
   String result = null;
   ArrayList statusResult = new ArrayList();
   statusResult.add("no");
   
   try {
    
    List nameValuePairs = new ArrayList(2);
          nameValuePairs.add(new BasicNameValuePair("username", userId));
          nameValuePairs.add(new BasicNameValuePair("password", password));
          nameValuePairs.add(new BasicNameValuePair("project_type", "Lewis"));
          
          
          httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));

          // Execute HTTP Post Request
          HttpResponse response = httpclient.execute(httppost);
          
    
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
     HttpEntity resEntity = response.getEntity();
     if (resEntity != null) {
      result = EntityUtils.toString(resEntity, HTTP.UTF_8);
      statusResult.set(0, "yes");// 代表帳密正確(經由你的webservice判斷)
     }
    } else {
     HttpEntity resEntity = response.getEntity();
     if (resEntity != null) {
      result = EntityUtils.toString(resEntity, HTTP.UTF_8);
      statusResult.set(0, "no");
     }
    }
   } catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   statusResult.add(result);
   if (statusResult.get(0).equals("yes")) {
    return statusResult;
   } else {
    return statusResult;
   }
  }
 }
}

沒有留言:

張貼留言