Detailed explanation of HTTP communication using java

Overview of HTTP communication

There are two main modes of HTTP communication: post mode and get mode. The former sends data to the server through the HTTP message entity, which has high security and no limit on the size of data transmission. The latter passes the query string of the URL to the server parameters and displays them in plaintext in the browser address bar, which has poor confidentiality and transmits 2048 characters at most. However, get requests are not good for nothing - get requests are mostly used to query (read resources) and have high efficiency. Post requests are used for operations with high security such as registration and login and writing data to the database.

In addition to post and get, HTTP communication has other ways! See HTTP request method

Preparation before coding

Before coding, we first create a servlet that receives the client's parameters (name and age) and responds to the client.

Using JDK to realize HTTP communication

Use urlconnection to implement get request

Instantiate a Java net. URL object; The openconnection () method of the URL object is used to get a Java net. URLConnection; Obtain the input stream through getinputstream () method of urlconnection object; Read the input stream; Close the resource.

Post request using httpurlconnection

java. net. Httpurlconnection is Java net. The subclass of URL provides more HTTP operations (getxxx and setXXX methods). This class defines a series of HTTP status codes:

HTTP communication using httpclient

Httpclient greatly simplifies the implementation of HTTP communication in JDK.

Maven dependency:

Get request

Post request

Httpclient is a sub project under Apache Jakarta common, which is used to provide an efficient, up-to-date and feature rich client programming toolkit supporting HTTP protocol, and it supports the latest versions and suggestions of HTTP protocol. Httpclient has been used in many projects, such as the other two famous open source projects cactus and htmlunit on Apache Jakarta.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>