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

Android 網路請求兩種寫法:HttpURLConnection 與 HttpClient 對照實作

編輯:關於 Android 程式設計

在 Android 上發送 HTTP GET 請求,常見有兩條路:一是 Java 標準的 HttpURLConnection,二是 Apache 的 HttpClient。下面把兩種寫法封裝在同一個 HttpHelper 工具類裡,方便直接對照差異。

HttpHelper.java 完整程式碼

public class HttpHelper {

    // 1: 標準的 Java 接口
    public static String getStringFromNet1(String param) {
        String result = "";
        try {
            URL url = new URL(param);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream is = conn.getInputStream();
                byte[] data = new byte[1024];
                int len = is.read(data);
                result = new String(data, 0, len);
                is.close();
                conn.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    // 2: Apache 接口
    public static String getStringFromNet2(String param) {
        String result = "";
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(param);
            HttpResponse response = client.execute(get);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

兩種方式的差異

HttpURLConnection 走的是標準 Java API,只需檢查 getResponseCode() 是否等於 HTTP_OK,再從 getInputStream() 逐段讀出位元組自行組字串,用完記得關流並 disconnect()。

HttpClient 則把細節都包好了:建立 DefaultHttpClient、下 HttpGet、執行後用 EntityUtils.toString() 一行就把 entity 轉成字串,程式碼乾淨得多。

實務上的提醒

  • 這兩個方法都是同步的,直接呼叫會阻塞。在 Android 上必須放到子執行緒(例如搭配 AsyncTask、Thread 或 Timer)執行,否則會觸發 NetworkOnMainThreadException。
  • 範例只用 1024 位元組的緩衝區讀一次,正式環境建議用迴圈讀完串流,並加上逾時設定與更完整的例外處理。
  • 記得在 AndroidManifest.xml 註冊 android.permission.INTERNET。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved