建立 HttpURLConnection

要建立新的 Android HTTP 客戶端 HttpURLConnection,請在 URL 例項上呼叫 openConnection()。由於 openConnection() 返回 URLConnection,你需要顯式轉換返回的值。

URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// do something with the connection

如果要建立新的 URL,還必須處理與 URL 解析相關的異常。

try {
    URL url = new URL("http://example.com");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    // do something with the connection
} catch (MalformedURLException e) {
    e.printStackTrace();
}

一旦讀取了響應主體並且不再需要連線,就應該通過呼叫 disconnect() 來關閉連線。

這是一個例子:

URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
    // do something with the connection
} finally {
    connection.disconnect();
}