Home > Java > javaTutorial > body text

Summary of connection, timeout, and shutdown usage of URLConnection

巴扎黑
Release: 2016-12-20 13:46:22
Original
1716 people have browsed it

HttpURLConnection can be used in Java to request WEB resources.

1. The categories of URL requests

are divided into two categories, GET and POST requests. The difference between the two is:
a:) The get request can obtain a static page, or you can put the parameters after the URL string and pass it to the servlet.
b:) The difference between post and get is that the parameters of post are not placed in In the URL string, it is placed in the body of the http request.

2. URLConnection object problem

Java code

URL url = new URL("http://localhost:8080/TestHttpURLConnectionPro.do");

URLConnection rulConnection = url.openConnection (); // The urlConnection object here is actually a URLConnection class generated based on the URL's

                                                                                                                                                                                  urlConnection class                                                                 urlConnection class         Object of type HttpURLConnection, in order to use

                                                                                                                                                                             

3. HttpURLConnection object parameter problem

Java code

// Set whether to output to httpUrlConnection. Because this is a post request, the parameters must be placed in the http body, so it needs to be set to true. The default is false;

httpUrlConnection.setDoOutput(true);

/ / Set whether to read from httpUrlConnection, the default is true;

httpUrlConnection.setDoInput(true);

// Post requests cannot use cache

httpUrlConnection.setUseCaches(false);

// Set The content type transmitted is determined to be a serializable java object

// (If this item is not set, when transmitting a serialized object, a java.io.EOFException may be thrown when the default WEB service is not of this type)

httpUrlConnection.setRequestProperty("Content-type", "application/x-java-serialized-object");

// Set the request method to "POST", the default is GET

httpUrlConnection.setRequestMethod("POST ");

// Connection, the configuration from url.openConnection() to this point in the above 2 items must be completed before connect,

                                                                                                                                         

Java code

// Here getOutputStream will implicitly connect (that is, just like calling the connect() method above,

// So it is okay not to call the above connect() during development).

OutputStream outStrm = httpUrlConnection.getOutputStream();

5. HttpURLConnection writing data and sending data issues

Java code

// Now build the object output stream object through the output stream object to achieve serializable output object.

ObjectOutputStream objOutputStrm = new ObjectOutputStream(outStrm);

//Write data to the object output stream, and the data will be stored in the memory buffer

objOutputStrm.writeObject(new String("I am test data") ; At this time, no more data can be written to the object output stream. The previously written data exists in the memory buffer.

// The prepared http request is officially sent to the server only when the getInputStream() function below is called.

objOutputStm.close();

// Call the getInputStream() function of the HttpURLConnection connection object,

// Send the complete HTTP request message encapsulated in the memory buffer to the server.

InputStream inStrm = httpConn.getInputStream(); // <===Note, the code segment that actually sends the request is here

// The above httpConn.getInputStream() method has been called, this HTTP request It has ended. The following output to the object output stream is meaningless.

// Even if the object output stream does not call the close() method, the following operation will not write any data to the object output stream.

// Therefore, when you want to resend data, you need to re-create the connection, re-set parameters, re-create the stream object, re-write the data,

// re-send the data (as for whether these operations need to be re-researched)

objOutputStm. writeObject(new String(""));

httpConn.getInputStream();

6. Post parameter method

Java code

OutputStream os = httpConn.getOutputStream();

           param = new String ();

                                                                =" + phoneNumber +

" "&msg=" + java.net.URLEncoder.encode(msg,"GBK "); ;

  os.write(param.getBytes());

7. Timeout setting to prevent the program from freezing and not continuing to execute in case of network abnormality

Java code

System.setProperty("sun.net.client.defaultConnectTimeout", "30000");

System.setProperty("sun.net.client.defaultReadTimeout", "30000");

where: sun.net. client.defaultConnectTimeout: timeout for connecting to the host (unit: milliseconds)

sun.net.client.defaultReadTimeout: timeout for reading data from the host (unit: millisecond)

JDK Versions before 1.5 can only be passed through Set these two system properties to control network timeouts. In 1.5, you can also use the following two methods of the parent class URLConnection of HttpURLConnection:

setConnectTimeout: Set the connection host timeout (unit: milliseconds)

setReadTimeout: Set the timeout for reading data from the host (unit: milliseconds)

For example:

HttpURLConnection urlCon = (HttpURLConnection)url.openConnection();

urlCon.setConnectTimeout(30000);

urlCon.setReadTimeout(30000);

Summary:

a : The connect() function of HttpURLConnection actually only establishes a tcp connection with the server and does not actually send an http request.

Whether it is post or get, the http request is actually not officially sent until the getInputStream() function of HttpURLConnection.

b: When sending a URL request using POST, the setting order of URL request parameters is the top priority.

All configurations of the connection object (those set functions)

must be executed before the connect() function. Finish. The write operation on outputStream must precede the read operation on inputStream.
These orders are actually determined by the format of the http request.
If the inputStream read operation precedes the outputStream write operation, an exception will be thrown:
java.net.ProtocolException: Cannot write output after reading input....

c: The http request actually consists of two parts,
One is the http header. All configurations about this http request are defined in the http header.
The other is the content. The
connect() function will generate http header information based on the configuration value of the HttpURLConnection object, so before calling the connect function,
all configurations must be prepared.
d: Immediately following the http header is the body of the http request. The content of the body is written through the outputStream stream.
In fact, the outputStream is not a network stream. It is a string stream at best. What is written into it is not It will be sent to the network immediately, but it will exist in the memory buffer. When the outputStream is closed, the http body will be generated based on the input content.
At this point, everything requested by http is ready. When the getInputStream() function is called, the prepared http request will be officially sent to the server, and then an input stream will be returned for reading the server's return information for this http request. Since the http
request has been sent out during getInputStream (including http header and body), so after the getInputStream() function
set the connection object (modify the http header information) or write to the outputStream (modify the body) Modifications)
are meaningless. Performing these operations will cause exceptions.



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template