创建 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();
}