2013年6月14日 星期五

Android程式設計 - HTTP資料傳遞(1)使用GET

假設伺服端httpget.php網頁如下,:
<?php
//宣告使用utf-8編碼
header("Content-Type:text/html; charset=utf-8");
$user=$_GET['login_user'];
$pass=$_GET['login_pw'];
echo "login_user=".$user.";login_pw=".$pass;
?>

我們可以先使用以下表單來驗證網頁功能
<html>
<body>
測試GET資料傳送:
<form method="GET" action="http://163.22.249.40/myPHP/httpget.php">
帳號:
<input type="text" name="login_user" size="20"value="sswu" /><br />
密碼:
<input type="text" name="login_pw" size="20" value="1234" /><br />
<input type="submit" name="btnSend" value="送出" /><br />
</form>
</body>
</html>

HTTP GET是將參數附加在URL之後,例如:http://my_webserver/httpget.php?login_user=sswu&login_pw=1234,Android中可使用HttpGet 物件進行HTTP GET資料傳遞,程式如下:

String Url = "http://my_webserver/httpget.php";
//設定GET參數
List getData = new ArrayList();
getData.add(new BasicNameValuePair("login_user", "sswu"));
getData.add(new BasicNameValuePair("login_pw", "0123"));
String result = httpGET(Url, getData);
if (result == null) {
//顯示錯誤訊息
}
        ...

    /**
     * Issue a GET request to the server.
     * @param url GET address.
     * @param params request parameters.
     */
    private String httpGET(String url, List params){
        //組合成http get格式
        StringBuilder sb = new StringBuilder();
        sb.append(url).append("?");
        for (NameValuePair nvp : params) {
            try{
                sb.append(nvp.getName()).append("=").append(URLEncoder.encode(nvp.getValue(), "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            sb.append('&');
        }
        sb.deleteCharAt(sb.length()-1);
        HttpGet get = new HttpGet(sb.toString());
        try {    
            //送出HTTP request並取得HTTP response
            HttpResponse httpResponse = new DefaultHttpClient().execute(get);
            //檢查狀態碼,200表示OK
            if (httpResponse.getStatusLine().getStatusCode()==200){
                //取出回應字串
                String strResult = EntityUtils.toString(httpResponse.getEntity());
                return strResult;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }