Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 網路編程:用 HttpClient 發送 GET 與 POST 請求

編輯:關於 Android 開發

Android 網路編程:用 HttpClient 發送 GET 與 POST 請求

HttpClient 是早期 Android 常見的網路請求方式,介面就兩個按鈕加一個顯示結果的文本框:一個負責發 GET,一個負責彈出登入框發 POST。雖然它在後續版本被標記為廢棄,但理解它的四步流程,對看懂 HTTP 請求的本質很有幫助。

GET 請求的標準四步:

1、建立 HttpClient 物件:HttpClient httpclient = new DefaultHttpClient();

2、建立代表請求的 HttpGet:HttpGet httpget = new HttpGet("https://www.baidu.com");

3、執行請求並取得回應物件 HttpResponse:httpclient.execute(httpget);

4、從回應中取出實體 HttpEntity:httpresponse.getEntity(),再從中讀內容。

public class HttpClientDemo extends Activity {
    private TextView response;
    private HttpClient httpclient;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 0x123) {
                response.append(msg.obj.toString() + "\n");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_client);
        httpclient = new DefaultHttpClient();
        response = findViewById(R.id.response);
    }

    /** 發送 GET 請求 */
    public void accessSecret(View v) {
        response.setText("");
        new Thread() {
            public void run() {
                HttpGet httpget = new HttpGet("https://localhost:8080/foo/secret.jsp");
                try {
                    HttpResponse httpresponse = httpclient.execute(httpget);
                    HttpEntity entity = httpresponse.getEntity();
                    if (entity != null) {
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(entity.getContent()));
                        String line;
                        while ((line = br.readLine()) != null) {
                            Message msg = new Message();
                            msg.what = 0x123;
                            msg.obj = line;
                            handler.sendMessage(msg);   // 交回 UI 執行緒更新
                        }
                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /** 彈出登入框並發送 POST 請求 */
    public void showLogin(View v) {
        final View loginDialog = getLayoutInflater().inflate(R.layout.login, null);
        new AlertDialog.Builder(this)
                .setTitle("登錄系統")
                .setView(loginDialog)
                .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        final String name = ((EditText) loginDialog.findViewById(R.id.name))
                                .getText().toString();
                        final String pass = ((EditText) loginDialog.findViewById(R.id.pass))
                                .getText().toString();
                        new Thread() {
                            public void run() {
                                try {
                                    HttpPost httppost = new HttpPost(
                                            "https://localhost:8080/foo/login.jsp");
                                    // 把參數封裝成名稱值對
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair("name", name));
                                    params.add(new BasicNameValuePair("pass", pass));
                                    httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                                    HttpResponse httpresponse = httpclient.execute(httppost);
                                    if (httpresponse.getStatusLine().getStatusCode() == 200) {
                                        String msg = EntityUtils.toString(httpresponse.getEntity());
                                        Toast.makeText(HttpClientDemo.this, msg,
                                                Toast.LENGTH_LONG).show();
                                    }
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }.start();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
}

幾點實務提醒:

· 網路請求一定要放在子執行緒,主執行緒做網路操作會直接拋 NetworkOnMainThreadException。

· 回主線更新 UI 有正規做法,用 Handler 是其一,也可以改用 runOnUiThread 或後來的 AsyncTask/RxJava。

· 上例中在子線寫 Looper.prepare()/loop() 去彈 Toast 並不是好習慣,容易把線卡住,建議一律交回主執行緒處理。

· 常見狀態碼:200 成功、301/302 重新導向、404 找不到資源、500 系列為伺服器端錯誤。

· 新專案請直接使用 OkHttp 或 Retrofit,並記得在清單中申請 android.permission.INTERNET 權限。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved