Google提供了两种不同的HttpURLConnection使用示例.
InputStream的closehttp://developer.android.com/training/basics/network-ops/connecting.html
// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
Run Code Online (Sandbox Code Playgroud)
HttpURLConnection的disconnecthttp://developer.android.com/reference/java/net/HttpURLConnection.html
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
}
Run Code Online (Sandbox Code Playgroud)
对于资源泄漏和性能考虑(不需要从头开始设置网络连接,因为我的应用程序将在大多数时间与同一服务器通信),我们是否应该
HttpURLConnection的disconnect唯一.InputStream的close唯一.HttpURLConnection的disconnect及InputStream的close(没见过这么正式至今例子).根据Oracle的Java,调用disconnect()可能会关闭底层套接字连接,如果连接是空闲的(不提取任何东西).这"表示在不久的将来不太可能使用同一个HttpUrlConnection实例向服务器发出其他请求" .您必须通过创建另一个来重新打开新的套接字连接HttpUrlConnection.
但是,Google已进行了修改,HttpUrlConnection以便可以重复使用套接字连接.在Android中,Socketa使用的底层HttpUrlConnection可以持久化并重用于多个请求.如果disconnect在完成请求后调用,它可以将套接字发送到包含其他空闲连接的池,准备重用.系统执行此操作以减少延迟.
从文档:
与其他Java实现不同,这不一定会关闭可以重用的套接字连接.您可以通过在发出任何HTTP请求之前将http.keepAlive系统属性设置为false来禁用所有连接重用.
所以你应该调用disconnect释放资源(流和套接字),但是释放的一些资源可能会被重用(即套接字将进入一个空闲套接字池,为下一个HttpUrlConnection实例准备好重用它).
至于为什么第一个例子没有调用disconnect(),那就是Java SE重用连接的方式(我想,已经有一段时间了).作者所做的是手动关闭InputStream连接并使套接字保持打开状态并空闲以便重用.第二个示例显示了Android上的正确方法.
总结:调用disconnect()Android将关闭任何InputStream或OutputStream用于连接,并可能将用于连接的套接字发送到池,准备重用于其他请求.所以,如果你打电话disconnect(),就没有必要打电话了InputStream#close().
| 归档时间: |
|
| 查看次数: |
1056 次 |
| 最近记录: |