I am using HTTPURLConnection
to connect to a web service. I know how to use HTTPURLConnection
but I want to understand how it works. Basically, I want to know the following:
HTTPURLConnection
try to establish a connection to the given URL?getOutputStream
and getInputStream
in layman's term? I notice that when the server I'm trying to connect to is down, I get an Exception
at getOutputStream
. Does it mean that HTTPURLConnection
will only start to establish a connection when I invoke getOutputStream
? How about the getInputStream
? Since I'm only able to get the response at getInputStream
, then does it mean that I didn't send any request at getOutputStream
yet but simply establishes a connection? Do HttpURLConnection
go back to the server to request for response when I invoke getInputStream
?openConnection
simply creates a new connection object but does not establish any connection yet?This question is related to
java
inputstream
httpurlconnection
outputstream
urlconnection
I went through the exercise to capture low level packet exchange, and found that network connection is only triggered by operations like getInputStream, getOutputStream, getResponseCode, getResponseMessage etc.
Here is the packet exchange captured when I try to write a small program to upload file to Dropbox.
Below is my toy program and annotation
/* Create a connection LOCAL object,
* the openConnection() function DOES NOT initiate
* any packet exchange with the remote server.
*
* The configurations only setup the LOCAL
* connection object properties.
*/
HttpURLConnection connection = (HttpURLConnection) dst.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
...//headers setup
byte[] testContent = {0x32, 0x32};
/**
* This triggers packet exchange with the remote
* server to create a link. But writing/flushing
* to a output stream does not send out any data.
*
* Payload are buffered locally.
*/
try (BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream())) {
outputStream.write(testContent);
outputStream.flush();
}
/**
* Trigger payload sending to the server.
* Client get ALL responses (including response code,
* message, and content payload)
*/
int responseCode = connection.getResponseCode();
System.out.println(responseCode);
/* Here no further exchange happens with remote server, since
* the input stream content has already been buffered
* in previous step
*/
try (InputStream is = connection.getInputStream()) {
Scanner scanner = new Scanner(is);
StringBuilder stringBuilder = new StringBuilder();
while (scanner.hasNextLine()) {
stringBuilder.append(scanner.nextLine()).append(System.lineSeparator());
}
}
/**
* Trigger the disconnection from the server.
*/
String responsemsg = connection.getResponseMessage();
System.out.println(responsemsg);
connection.disconnect();
On which point does HTTPURLConnection try to establish a connection to the given URL?
It's worth clarifying, there's the 'UrlConnection' instance and then there's the underlying Tcp/Ip/SSL socket connection, 2 different concepts. The 'UrlConnection' or 'HttpUrlConnection' instance is synonymous with a single HTTP page request, and is created when you call url.openConnection(). But if you do multiple url.openConnection()'s from the one 'url' instance then if you're lucky, they'll reuse the same Tcp/Ip socket and SSL handshaking stuff...which is good if you're doing lots of page requests to the same server, especially good if you're using SSL where the overhead of establishing the socket is very high.
Tim Bray presented a concise step-by-step, stating that openConnection() does not establish an actual connection. Rather, an actual HTTP connection is not established until you call methods such as getInputStream() or getOutputStream().
http://www.tbray.org/ongoing/When/201x/2012/01/17/HttpURLConnection
On which point does
HTTPURLConnection
try to establish a connection to the given URL?
On the port named in the URL if any, otherwise 80 for HTTP and 443 for HTTPS. I believe this is documented.
On which point can I know that I was able to successfully establish a connection?
When you call getInputStream()
or getOutputStream()
or getResponseCode()
without getting an exception.
Are establishing a connection and sending the actual request done in one step/method call? What method is it?
No and none.
Can you explain the function of
getOutputStream()
andgetInputStream()
in layman's term?
Either of them first connects if necessary, then returns the required stream.
I notice that when the server I'm trying to connect to is down, I get an Exception at
getOutputStream()
. Does it mean thatHTTPURLConnection
will only start to establish a connection when I invokegetOutputStream()
? How about thegetInputStream()
? Since I'm only able to get the response atgetInputStream()
, then does it mean that I didn't send any request atgetOutputStream()
yet but simply establishes a connection? DoHttpURLConnection
go back to the server to request for response when I invokegetInputStream()
?
See above.
Am I correct to say that
openConnection()
simply creates a new connection object but does not establish any connection yet?
Yes.
How can I measure the read overhead and connect overhead?
Connect: take the time getInputStream()
or getOutputStream()
takes to return, whichever you call first. Read: time from starting first read to getting the EOS.
Source: Stackoverflow.com