explain the HttpURLConnection connection process
来源:互联网 发布:淘宝查号官网 编辑:程序博客网 时间:2024/06/06 03:03
try { // instantiate the URL object with the target URL of the resource to request URL url = new URL("http://www.example.com/comment"); // instantiate the HttpURLConnection with the URL object - A new connection is opened every time by calling the openConnection method of the protocol handler for this URL. // 1. This is the point where the connection is opened. HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // set connection output to true connection.setDoOutput(true); // instead of a GET, we're going to send using method="POST" connection.setRequestMethod("POST"); // instantiate OutputStreamWriter using the output stream, returned from getOutputStream, that writes to this connection. // 2. This is the point where you'll know if the connection was successfully established. If an I/O error occurs while creating the output stream, you'll see an IOException. OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); // write data to the connection. This is data that you are sending to the server // 3. No. Sending the data is conducted here. We established the connection with getOutputStream writer.write("message=" + message); // Closes this output stream and releases any system resources associated with this stream. At this point, we've sent all the data. Only the outputStream is closed at this point, not the actual connection writer.close(); // if there is a response code AND that response code is 200 OK, do stuff in the first if block if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { // OK // otherwise, if any other status code is returned, or no status code is returned, do stuff in the else block } else { // Server returned HTTP error code. } } catch (MalformedURLException e) { // ... } catch (IOException e) { // ... }
From getOutputStream:
Returns an output stream that writes to this connection.
Basically, I think you have a good understanding of how this works, so let me just reiterate in laymans terms. getOutputStream basically opens a connection stream, with the intention of writing data to the server. In the above code example "message" could be a comment that we're sending to the server that represents a comment left on a post. When you see getOutputStream, you're opening the connectionstream for writing, but you don't actually write any data until you call writer.write("message=" + message);
.
From getInputStream():
Returns an input stream that reads from this open connection. A SocketTimeoutException can be thrown when reading from the returned input stream if the read timeout expires before data is available for read.
getInputStream does the opposite. Like getOutputStream, it also opens a connection stream, but the intent is to read data from the server, not write to it. If the connection or stream-opening fails, you'll see a SocketTimeoutException.
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?
Keep in mind that sending a request and sending data are two different operations. When you invokegetOutputStream or getInputStream url.openConnection()
, you send a request to the server to establish a connection. There is a handshake that occurs where the server sends back an acknowledgement to you that the connection is established. It is then at that point in time that you're prepared to send or receive data. Thus, you do not need to call getOutputStream to establish a connection open a stream, unless your purpose for making the request is to send data.
In laymans terms, making a getInputStream request is the equivalent of making a phone call to your friend's house to say "Hey, is it okay if I come over and borrow that pair of vice grips?" and your friend establishes the handshake by saying, "Sure! Come and get it". Then, at that point, the connection is made, you walk to your friend's house, knock on the door, request the vice grips, and walk back to your house.
Using a similar example for getOutputStream would involve calling your friend and saying "Hey, I have that money I owe you, can I send it to you"? Your friend, needing money and sick inside that you kept it for so long, says "Sure, come on over you cheap bastard". So you walk to your friend's house and "POST" the money to him. He then kicks you out and you walk back to your house.
Now, continuing with the laymans example, let's look at some Exceptions. If you called your friend and he wasn't home, that could be a 500 error. If you called and got a disconnected number message because your friend is tired of you borrowing money all the time, that's a 404 page not found. If your phone is dead because you didn't pay the bill, that could be an IOException. (NOTE: This section may not be 100% correct. It's intended to give you a general idea of what's happening in laymans terms.)
Question #5:
Yes, you are correct that openConnection simply creates a new connection object but does not establish it. The connection is established when you call either getInputStream or getOutputStream.
openConnection creates a new connection object. From the URL.openConnection javadocs:
A new connection is opened every time by calling the openConnection method of the protocol handler for this URL.
The connection is established when you call openConnection, and the InputStream, OutputStream, or both, are called when you instantiate them.
Question #6:
To measure the overhead, I generally wrap some very simple timing code around the entire connection block, like so:
long start = System.currentTimeMillis();log.info("Time so far = " + new Long(System.currentTimeMillis() - start) );// run the above example code herelog.info("Total time to send/receive data = " + new Long(System.currentTimeMillis() - start) );
I'm sure there are more advanced methods for measuring the request time and overhead, but this generally is sufficient for my needs.- explain the HttpURLConnection connection process
- Explain tables does not exist. Check the explain plan properties for this database connection.
- The Process of TCP Connection and State Transfer
- TCP Connection Establishment Process: The "Three-Way Handshake"
- 【Oracle】connection、session、process
- Gradle sync failed: The first result from the daemon was empty. Most likely the process died immediately after connection
- HttpURLConnection中connection.getInputStream()报异常FileNotFoundException
- Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection
- IPC(Inter Process Connection) 总结笔记(1)
- Zend Server提示Error: Could not locate a free PHP process from the "application/x-httpd-php" pool within the 'Connection Timeout'.
- The C# Design Process
- The Linux Process Manager
- The Inspection Process
- The process of testing
- The C# Design Process
- The Linux Process Manager
- The Kernel Boot Process
- The Linux Boot Process
- ubuntu 编译源代码 ,找不到glib或者glib版本不对
- 关于Java权限控制算法
- DB2 存储过程几个例子
- 写尽凄凉.沧桑.却写不出那最后一抹忧伤:伤感日志
- 删除表删除约束条件
- explain the HttpURLConnection connection process
- 个人所得税计算器、
- NoSQL 之 Morphia 操作 MongoDB
- linux下system函数
- IIS日志时间设置和网站IIS日志的设置与搜索引擎爬虫痕迹的分析
- iOS检查网络是否连接
- linux驱动学习(九) usb设备驱动的初步认知
- 在用力的十指紧扣,也只会各自散落,只能随缘了
- Ashx 文件