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

Android 開發實踐:URL、URLConnection、HttpURLConnection 與 HttpClient 網絡通信全解

編輯:關於 Android 程式設計

Android 沿用了 JDK 提供的 URL、URLConnection 等網絡通信 API,並在此基礎上引入了更貼合移動端的 HttpURLConnection 與 Apache 的 HttpClient。本文按由底層到上層的順序梳理這套體系。

一、認識 URL

URL(Uniform Resource Locator,統一資源定位符)是指向互聯網資源的指針,格式為:

protocol://host:port/resourceName

補充一點:JDK 中還有 URI(統一資源標識符)類,它只負責標識資源,不承擔定位職責,兩者用途不同。

拿到 URL 對象後,可以調用一系列方法解析其各部分,或直接訪問對應資源:

String getFile()          // 獲取資源文件名
String getHost()          // 獲取主機名
String getPath()          // 獲取路徑部分
int    getPort()          // 獲取端口號
String getProtocol()      // 獲取協議名
String getQuery()         // 獲取查詢字符串
URLConnection openConnection()  // 返回表示遠程連接的 URLConnection 對象
InputStream  openStream()       // 打開連接並返回讀取資源的輸入流

二、使用 URL 讀取網絡資源

openStream() 是最便捷的下載方式,一行即可拿到資源的輸入流:

public class URLTest extends Activity {
    private Bitmap bitmap;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new Thread() {
            public void run() {
                try {
                    URL url = new URL("https://avatar.csdn.net/D/F/D/1_smartbetter.jpg");

                    // 解析輸入流中的圖片
                    InputStream is = url.openStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    is.close();

                    // 將圖片下載到本地
                    is = url.openStream();
                    OutputStream os = openFileOutput("icon.jpg", MODE_PRIVATE);
                    byte[] buff = new byte[1024];
                    int hasRead = 0;
                    while ((hasRead = is.read(buff)) > 0) {
                        os.write(buff, 0, hasRead);
                    }
                    is.close();
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}

別忘了在清單文件中加入 android.permission.INTERNET 權限,並將網絡操作放到子線程中執行——主線程網絡訪問在較新版本系統上會直接拋出 NetworkOnMainThreadException。

三、使用 URLConnection 提交請求

openConnection() 返回的 URLConnection 對象代表應用與遠程資源之間的連接,通過它既能發送請求,也能讀取響應。下面的工具類封裝了 GET 與 POST 兩種請求:

public class GetPostUtil {

    /** 向指定 URL 發送 GET 請求
     *  @param url    請求地址
     *  @param params 請求參數,形如 name1=value1&name2=value2
     *  @return 遠程資源的響應 */
    public static String doGet(String url, String params) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlName = url + "?" + params;
            URL realUrl = new URL(urlName);
            URLConnection conn = realUrl.openConnection();
            // 設置通用請求頭
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.connect();

            Map<String, List<String>> map = conn.getHeaderFields();
            for (String key : map.keySet()) {
                System.out.println(key + ":" + map.get(key));
            }

            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += "\n" + line;
            }
        } catch (Exception e) {
            System.out.println("請求異常!" + e);
        } finally {
            try {
                if (in != null) in.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /** 向指定 URL 發送 POST 請求
     *  @param params 請求參數,形如 name1=value1&name2=value2
     *  @return 遠程資源的響應 */
    public static String doPost(String url, String params) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            // 發送 POST 請求必須設置以下兩行
            conn.setDoOutput(true);
            conn.setDoInput(true);

            out = new PrintWriter(conn.getOutputStream());
            out.print(params);
            out.flush();

            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += "\n" + line;
            }
        } catch (Exception e) {
            System.out.println("請求異常!" + e);
        } finally {
            try {
                if (out != null) out.close();
                if (in != null) in.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
}

四、使用 HttpURLConnection

HttpURLConnection 繼承自 URLConnection,針對 HTTP 協議做了增強,提供了一批便捷方法:

int    getResponseCode()             // 獲取服務器響應碼
String getResponseMessage()          // 獲取響應消息
String getRequestMethod()            // 獲取當前請求方法
void   setRequestMethod(String m)    // 設置請求方法

五、使用 HttpClient

HttpClient 是 Apache 的開源項目,用於發送 HTTP 請求並接收響應。它不緩存服務器響應、不執行頁面中的 JS、也不做任何 HTML 解析,本質上是增強版的 HttpURLConnection。

public class HttpClientTest extends Activity {
    HttpClient httpClient;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        httpClient = new DefaultHttpClient();
    }

    /** GET 請求 */
    public void doHttpClientGet(View view) {
        new Thread() {
            @Override
            public void run() {
                HttpGet get = new HttpGet("https://192.168.1.10:8080/server/page.jsp");
                try {
                    HttpResponse httpResponse = httpClient.execute(get);
                    HttpEntity entity = httpResponse.getEntity();
                    if (entity != null) {
                        BufferedReader br = new BufferedReader(
                            new InputStreamReader(entity.getContent()));
                        String line;
                        while ((line = br.readLine()) != null) {
                            System.out.println("服務器響應:" + line);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /** POST 請求,模擬登錄 */
    public void doHttpClientPost(View view) {
        final String name = "zhangsan";
        final String pass = "123";
        new Thread() {
            @Override
            public void run() {
                try {
                    HttpPost post = new HttpPost("https://192.168.1.10:8080/server/login.jsp");
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("name", name));
                    params.add(new BasicNameValuePair("pass", pass));
                    post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

                    HttpResponse response = httpClient.execute(post);
                    if (response.getStatusLine().getStatusCode() == 200) {
                        String msg = EntityUtils.toString(response.getEntity());
                        System.out.println(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}

需要提醒的是,Apache HttpClient 自 Android 5.1 起被標記為廢棄,並在 Android 6.0 中從框架裡移除,新項目不應再依賴它。

六、第三方網絡框架

工程實踐中更常見的是成熟的三方庫:

  • Android-async-http
  • Afinal 框架
  • xUtils3 框架
  • 以及目前主流的 OkHttp、Retrofit、Volley 等

它們在連接池複用、攔截器鏈、Gzip 壓縮、異步回調與 API 建模上都有更完善的抽象,能顯著減少重複的樣板代碼。

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