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

Android HTTP 通信實戰:HttpURLConnection、HttpClient 與 loopj 三種方案對比

編輯:關於 Android 程式設計

做 Android 網絡請求,常見有幾條路:原生 HttpURLConnection、Apache HttpClient,以及成熟的第三方框架。下面按這三類分別給出可運行的寫法,並附上最簡陋的 Java Web 後端作為對照,方便你把整條鏈路跑通。


一、HttpURLConnection

官方推薦的做法。它的使用步驟很清晰:

1. 呼叫 URL.openConnection() 並轉型為 HttpURLConnection;

2. 準備請求:主要屬性是其 URI,請求頭可攜帶認證資訊、期望的內容類型、Session Cookie 等;

3. 如有請求體,需先 setDoOutput(true),然後向 getOutputStream() 寫資料;

4. 讀取響應:響應頭包含內容類型、長度、修改時間等中繼資料,響應體從 getInputStream() 讀;無 body 時返回空串流;

5. 讀完後呼叫 disconnect() 釋放資源,使其可被關閉或複用。

最簡要的 GET:

URL url = new URL("https://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    readStream(in);
} finally {
    urlConnection.disconnect();
}

幾個值得記住的特性:呼叫 URL.openConnection() 時若 scheme 是 https,會返回 HttpsURLConnection,可以自定義 HostnameVerifier 與 SSLSocketFactory;它會自動跟隨最多五次 HTTP 重定向(但不處理 HTTPS 與 HTTP 互跳);出錯時 getInputStream() 會拋 IOException,此時可用 getErrorStream() 讀取錯誤響應體,響應頭照常用 getHeaderFields() 讀。

上傳資料時,若已知 body 長度,建議呼叫 setFixedLengthStreamingMode(int);長度未知則用 setChunkedStreamingMode(int)。否則 HttpURLConnection 會先把整個請求體緩存進記憶體再發送,浪費堆空間並增加延遲。

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
    urlConnection.setDoOutput(true);
    urlConnection.setChunkedStreamingMode(0);
    OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
    writeStream(out);
    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    readStream(in);
} finally {
    urlConnection.disconnect();
}

封裝成工具類

public class NetUtils1 {
    private static final String TAG = "NetUtils1";
    private static final String URL =
            "https://10.10.39.11:8080/Androiddata/Servletdata";

    /** POST 登陸 */
    public static String loginOfPost(String userName, String password) {
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) new URL(URL).openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(5000);
            conn.setDoOutput(true);   // 允許輸出,否則無法寫入請求體

            String data = "username=" + userName + "&password=" + password;
            OutputStream out = conn.getOutputStream();
            out.write(data.getBytes());
            out.flush();
            out.close();

            if (conn.getResponseCode() == 200) {
                return getStringFromInputStream(conn.getInputStream());
            } else {
                Log.i(TAG, "訪問失敗" + conn.getResponseCode());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) conn.disconnect();
        }
        return null;
    }

    /** GET 登陸 */
    public static String loginOfGet(String userName, String password) {
        HttpURLConnection conn = null;
        try {
            String data = "username=" + URLEncoder.encode(userName, "utf-8")
                    + "&password=" + URLEncoder.encode(password, "UTF-8");
            conn = (HttpURLConnection) new URL(URL + "?" + data).openConnection();
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(5000);

            if (conn.getResponseCode() == 200) {
                return getStringFromInputStream(conn.getInputStream());
            } else {
                Log.i(TAG, "訪問失敗" + conn.getResponseCode());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) conn.disconnect();
        }
        return null;
    }

    /** 流轉字串 */
    private static String getStringFromInputStream(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        is.close();
        String html = baos.toString();
        baos.close();
        return html;
    }
}

調用時記得放到子線程,再切回主線程更新 UI:

public void doGet(View v) {
    final String userName = etUserName.getText().toString();
    final String password = etPassword.getText().toString();
    new Thread(() -> {
        final String state = NetUtils1.loginOfGet(userName, password);
        runOnUiThread(() ->
                Toast.makeText(MainActivity.this, "返回:" + state,
                        Toast.LENGTH_SHORT).show());
    }).start();
}

二、HttpClient(含 GET / POST)

public class NetUtils2 {
    private static final String TAG = "NetUtils222";
    private static final String URL =
            "https://10.10.39.11:8080/Androiddata/Servletdata";

    /** POST */
    public static String loginOfPost(String userName, String password) {
        HttpClient client = null;
        try {
            client = new DefaultHttpClient();
            HttpPost post = new HttpPost(URL);

            List<NameValuePair> parameters = new ArrayList<>();
            parameters.add(new BasicNameValuePair("username", userName));
            parameters.add(new BasicNameValuePair("password", password));

            // 必須指定字元集,否則服務端取到的中文會亂碼
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
            post.setEntity(entity);

            HttpResponse response = client.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                return getStringFromInputStream(response.getEntity().getContent());
            } else {
                Log.i(TAG, "請求失敗" + statusCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (client != null) client.getConnectionManager().shutdown();
        }
        return null;
    }

    /** GET */
    public static String loginOfGet(String userName, String password) {
        HttpClient client = null;
        try {
            client = new DefaultHttpClient();
            String data = "username=" + userName + "&password=" + password;
            HttpGet get = new HttpGet(URL + "?" + data);

            HttpResponse response = client.execute(get);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                return getStringFromInputStream(response.getEntity().getContent());
            } else {
                Log.i(TAG, "請求失敗" + statusCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (client != null) client.getConnectionManager().shutdown();
        }
        return null;
    }
}

需要說明的是,Apache HttpClient 從 Android 5.1 起已被標記為廢棄,後續版本逐步移除,新專案不建議再使用,這裡保留是為了理解歷史程式碼。


三、loopj 的 AsyncHttpClient

框架化之後,GET / POST 與回呼都變得非常輕量:

public void doGet(View v) {
    String userName = etUserName.getText().toString();
    String password = etPassword.getText().toString();
    AsyncHttpClient client = new AsyncHttpClient();
    try {
        String data = "username=" + URLEncoder.encode(userName, "UTF-8")
                + "&password=" + URLEncoder.encode(password, "UTF-8");
        client.get(URL + "?" + data, new MyResponseHandler());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

public void doPost(View view) {
    AsyncHttpClient client = new AsyncHttpClient();
    RequestParams params = new RequestParams();
    params.put("username", etUserName.getText().toString());
    params.put("password", etPassword.getText().toString());
    client.post(URL, params, new MyResponseHandler());
}

class MyResponseHandler extends AsyncHttpResponseHandler {
    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
        Toast.makeText(MainActivity2.this,
                "成功: statusCode: " + statusCode
                        + ", body: " + new String(responseBody),
                Toast.LENGTH_LONG).show();
    }

    @Override
    public void onFailure(int statusCode, Header[] headers,
                          byte[] responseBody, Throwable error) {
        Toast.makeText(MainActivity2.this, "失敗: statusCode: " + statusCode,
                Toast.LENGTH_LONG).show();
    }
}

它自帶線程池與二進制/字串/JSON 等預置 ResponseHandler,並支援重試與 Cookie 持久化,對於快速搭原型很方便。


四、最簡陋的後端做對照

一個 Servlet 就夠了:

@WebServlet(name = "Servletdata", urlPatterns = "/Servletdata")
public class Servletdata extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if ("sdingba".equals(username) && "123".equals(password)) {
            response.getOutputStream().write("success".getBytes());
        } else {
            response.getOutputStream().write("error".getBytes());
        }
    }
}

整條鏈路跑通之後,實際專案裡通常會再往上封一層:統一處理狀態碼與業務錯誤碼、加上攔截器做簽名與 token 注入、用 JSON 而非自由文本作為數據格式。關於 HTTP 通信,RxJava + Retrofit、OkHttp、Volley 等都是不錯的選擇,值的投入時間去深入了解。

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