2013年6月14日 星期五

Android程式設計 - HTTP資料傳遞(2)使用POST

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

我們可以先使用以下表單來驗證網頁功能
<html>
<body>
測試POST資料傳送:
<form method="POST" action="http://163.22.249.40/myPHP/httppost.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 POST與HTTP GET主要差異在於參數資料傳遞方式,使用POST方式時必須使用setEntity()設定POST參數,程式如下:

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

    /**
     * Issue a POST request to the server.
     * @param url POST address.
     * @param params request parameters.
     */
    private String httpPOST(String url, List params){ 
        HttpPost post = new HttpPost(url);
        try {
            //送出HTTP request
            post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            //取得HTTP response
            HttpResponse httpResponse = new DefaultHttpClient().execute(post);
            //檢查狀態碼,200表示OK
            if (httpResponse.getStatusLine().getStatusCode()==200){
                //取出回應字串
                String strResult = EntityUtils.toString(httpResponse.getEntity());
                return strResult;
            }
        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }