search
HomeJavajavaTutorialSummary of connection, timeout, and shutdown usage of URLConnection

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(); //

// 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.



Statement
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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools