[Android] 透過HTTP Request進行後端資料存取(以PHP為例)


在開發提供網路服務的App的首要目標,就是必須瞭解Android如何藉由HTTP Request向後端存取資料,Android提供兩種呼叫HTTP服務的類別:(1) Apache HttpClient (2) HttpUrlConnection。


Apache HttpClient有完整且彈性的API可供呼叫,但相對來說容量較大,在pre-Gingerbread表現較好(HttpUrlConnection在Froyo之前的版本有Bug);而HttpUrlConnection屬於較為輕量易擴充的類別,在Gingerbread之後修正bug後,它的簡易性與小容量是開發網路服務App較好的選擇。

本文將以Apache HttpClient為對象,說明Application如何將資料傳送給後端伺服器,以及如何接收回傳的資料。

程式碼說明

以下範例將以常見的登入功能為例,將使用者輸入的帳號、密碼傳送給後端PHP處理,並回傳登入是否成功的訊息。

一、建立Layout XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Account: " />
    <EditText 
     android:id="@+id/acc_txt"
     android:layout_width="120dp"
     android:layout_height="wrap_content"
    />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Password: " />
    <EditText 
     android:id="@+id/pwd_txt"
     android:password="true"
     android:layout_width="120dp"
     android:layout_height="wrap_content"
    />
    <Button 
        android:id="@+id/login_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Login"
        android:onClick="onLogin"
    />
</LinearLayout>
二、建立HttpPost物件並設定其附帶的資料:所傳送的資料是以key-value pair的型式呈現,再透過UrlEncodedFormEntity()將其轉換為HttpEntity(注意!可以根據自己的需要變更charset)。
HttpClient client = new DefaultHttpClient();     
try {
 HttpPost post = new HttpPost("your url");
         
 //setup post variables
 List< NameValuePair> vars=new ArrayList< NameValuePair>();
 vars.add(new BasicNameValuePair("name",accText.getText().toString()));
 vars.add(new BasicNameValuePair("pwd",pwdText.getText().toString()));
 post.setEntity(new UrlEncodedFormEntity(vars,HTTP.UTF_8));
}
三、取得Server Response:透過在呼叫execute時,代入ResponseHandler可將HTTP Response以指定的資料型態回傳,同時也示範了如何將回傳的中文內容轉為UTF-8編碼。
//Setup response handler
ResponseHandler< String> h=new BasicResponseHandler();
String response=new String(client.execute(post,h).getBytes(),HTTP.UTF_8);
Toast.makeText(this, response, Toast.LENGTH_LONG).show();

四、在AndroidManifest加入存取網路permission
<uses-permission android:name="android.permission.INTERNET"/>

後端程式碼(PHP)
//get http request parameters
import_request_variables("gp");
    
//check account and password
if($acc=='admin'&&$pwd=='1234'){
  print_r('Welcome back!'.$account);
}else{
  print_r("帳號密碼錯誤!");
}

留言

這個網誌中的熱門文章

[Android] layout_weight的妙用-讓View的大小以百分比率顯示(proportionate size)

[Android] 內部儲存體(Internal Storage)的檔案系統讀寫(File I/O)

【海外婚紗】造型篇-我的超人新祕Sunny-Yang