虽然我在模拟器中运行google android示例代码,但我有一个问题。在不调用connect()方法的情况下,服务器请求运行良好。它是干什么用的?我已注释掉“ connection.connect();”而且它仍然像什么都没有改变一样工作。是否应该显式调用connect()?
*开发环境:Android Studio + openJDK 1.8 +模拟器
private String downloadUrl(URL url) throws IOException {
InputStream stream = null;
HttpsURLConnection connection = null;
String result = null;
try {
connection = (HttpsURLConnection) url.openConnection();
// Timeout for reading InputStream arbitrarily set to 3000ms.
connection.setReadTimeout(3000);
// Timeout for connection.connect() arbitrarily set to 3000ms.
connection.setConnectTimeout(3000);
// For this use case, set HTTP method to GET.
connection.setRequestMethod("GET");
// Already true by default but setting just in case; needs to be true since this request
// is carrying an input (response) body.
connection.setDoInput(true);
// Open communications link (network traffic occurs here).
// connection.connect(); <======================================== I have commented out
publishProgress(DownloadCallback.Progress.CONNECT_SUCCESS);
int responseCode = connection.getResponseCode();
if (responseCode != HttpsURLConnection.HTTP_OK) {
throw new IOException("HTTP error code: " + responseCode);
}
// Retrieve the response body as an InputStream.
stream = connection.getInputStream();
publishProgress(DownloadCallback.Progress.GET_INPUT_STREAM_SUCCESS, 0);
if (stream != null) {
// Converts Stream to String with max length of 500.
result = readStream(stream, 500);
publishProgress(DownloadCallback.Progress.PROCESS_INPUT_STREAM_SUCCESS, 0);
}
} finally {
// Close Stream and disconnect HTTPS connection.
if (stream != null) {
stream.close();
}
if (connection != null) {
connection.disconnect();
}
}
return result;
}
A connect()
呼叫在那里不是必需的。当您调用getResponseCode()
时,这将导致HttpURLConnection
建立基础连接,发送请求并等待直到响应到达……如果这些事情尚未发生。
这同时适用于Java SE和Android实现。