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

Android 使用 HttpURLConnection 與 HttpClient 實現 GET/POST 請求

編輯:關於 Android 程式設計

網絡請求是 Android 開發的基礎能力。本文分別用 HttpURLConnection 和 HttpClient 演示如何發送 GET 與 POST 請求。

一、HttpURLConnection 的 GET

GET 請求把參數拼接在 URL 後,開啟連接後讀取輸入流即可。注意網絡操作必須放在子線程,並透過 Handler 把結果回傳主線程更新 UI:

public void send() {
    String target = "";
    target = "https://192.168.1.66:8081/blog/index.jsp?content="
            + base64(content.getText().toString().trim());
    URL url;
    try {
        url = new URL(target);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
        BufferedReader buffer = new BufferedReader(in);
        String inputLine = null;
        while ((inputLine = buffer.readLine()) != null) {
            result += inputLine + "\n";
        }
        in.close();
        urlConn.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

// 對字符串進行 Base64 編碼並做 URL 編碼
public String base64(String content) {
    try {
        content = Base64.encodeToString(content.getBytes("utf-8"), Base64.DEFAULT);
        content = URLEncoder.encode(content);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return content;
}

二、HttpURLConnection 的 POST

POST 請求把參數寫入輸出流,需設置請求方式與內容類型:

public void send() {
    String target = "https://192.168.1.66:8081/blog/dealPost.jsp";
    URL url;
    try {
        url = new URL(target);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setRequestMethod("POST");
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setInstanceFollowRedirects(true);
        urlConn.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");

        DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
        String param = "nickname=" + URLEncoder.encode(nickname.getText().toString(), "utf-8")
                + "&content=" + URLEncoder.encode(content.getText().toString(), "utf-8");
        out.writeBytes(param);
        out.flush();
        out.close();

        if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
            BufferedReader buffer = new BufferedReader(in);
            String inputLine = null;
            while ((inputLine = buffer.readLine()) != null) {
                result += inputLine + "\n";
            }
            in.close();
        }
        urlConn.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

三、HttpClient 的 GET

與 HttpURLConnection 的 GET 相比,僅 send 方法不同:

public void send() {
    String target = "https://192.168.1.66:8081/blog/deal_httpclient.jsp?param=get";
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpRequest = new HttpGet(target);
    HttpResponse httpResponse;
    try {
        httpResponse = httpclient.execute(httpRequest);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            result = EntityUtils.toString(httpResponse.getEntity());
        } else {
            result = "請求失敗!";
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

四、HttpClient 的 POST

同樣地,僅 send 方法不同,POST 參數封裝進 NameValuePair 列表:

public void send() {
    String target = "https://192.168.1.66:8081/blog/deal_httpclient.jsp";
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httpRequest = new HttpPost(target);

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("param", "post"));
    params.add(new BasicNameValuePair("nickname", nickname.getText().toString()));
    params.add(new BasicNameValuePair("content", content.getText().toString()));
    try {
        httpRequest.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
        HttpResponse httpResponse = httpclient.execute(httpRequest);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            result += EntityUtils.toString(httpResponse.getEntity());
        } else {
            result = "請求失敗!";
        }
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

實踐中,GET 適合獲取數據、參數可見且長度有限;POST 適合提交敏感或大數據量內容,參數放在請求體中更安全。無論哪種方式,都要牢記把網絡請求放到子線程執行。

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