Home Java javaTutorial Detailed explanation of http communication using JAVA

Detailed explanation of http communication using JAVA

Jan 05, 2017 pm 02:26 PM

Http Communication Overview

Http communication mainly has two methods: POST method and GET method. The former sends data to the server through Http message entities, which has high security and no limit on data transmission size. The latter passes the query string of the URL to the server parameters and displays them in the browser address bar in plain text. It has poor confidentiality and can transmit up to 2048 characters. . But GET requests are not useless - GET requests are mostly used for querying (reading resources) and are highly efficient. POST requests are used for registration, login and other operations with high security and writing data to the database.

In addition to POST and GET, there are other ways of http communication! Please see the http request method

Preparation before encoding

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

@WebServlet(urlPatterns={"/demo.do"})
public class DemoServlet extends HttpServlet {
 
  private static final long serialVersionUID = 1L;
 
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
 
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    String name = request.getParameter("name");
    String age = request.getParameter("age");
    PrintWriter pw = response.getWriter();
    pw.print("您使用GET方式请求该Servlet。<br />" + "name = " + name + ",age = " + age);
    pw.flush();
    pw.close();
  }
 
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
 
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    String name = request.getParameter("name");
    String age = request.getParameter("age");
    PrintWriter pw = response.getWriter();
    pw.print("您使用POST方式请求该Servlet。<br />" + "name = " + name + ",age = " + age);
    pw.flush();
    pw.close();
  }
 
}
Copy after login

Use JDK to implement http communication

Use URLConnection to implement GET request

Instantiate a java.net.URL object;
Through the openConnection() method of the URL object Get a java.net.URLConnection;
Get the input stream through the getInputStream() method of the URLConnection object;
Read the input stream;
Close the resource.

public void get() throws Exception{
 
  URL url = new URL("http://127.0.0.1/http/demo.do?name=Jack&age=10");
  URLConnection urlConnection = url.openConnection();                          // 打开连接
  BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"utf-8")); // 获取输入流
  String line = null;
  StringBuilder sb = new StringBuilder();
  while ((line = br.readLine()) != null) {
    sb.append(line + "\n");
  }
 
  System.out.println(sb.toString());
}
Copy after login

Detailed explanation of http communication using JAVA

Use HttpURLConnection to implement POST requests

java.net.HttpURLConnection is a subclass of java.net.URL, providing more information about http Operations (getXXX and setXXX methods). This class defines a series of HTTP status codes:

Detailed explanation of http communication using JAVA

public void post() throws IOException{
 
  URL url = new URL("http://127.0.0.1/http/demo.do");
  HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
 
  httpURLConnection.setDoInput(true);
  httpURLConnection.setDoOutput(true);    // 设置该连接是可以输出的
  httpURLConnection.setRequestMethod("POST"); // 设置请求方式
  httpURLConnection.setRequestProperty("charset", "utf-8");
 
  PrintWriter pw = new PrintWriter(new BufferedOutputStream(httpURLConnection.getOutputStream()));
  pw.write("name=welcome");          // 向连接中输出数据(相当于发送数据给服务器)
  pw.write("&age=14");
  pw.flush();
  pw.close();
 
  BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"utf-8"));
  String line = null;
  StringBuilder sb = new StringBuilder();
  while ((line = br.readLine()) != null) {  // 读取数据
    sb.append(line + "\n");
  }
 
  System.out.println(sb.toString());
}
Copy after login

Detailed explanation of http communication using JAVA

##Using httpclient for http communication

httpclient greatly Simplified the implementation of http communication in JDK.

maven dependency:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.3.6</version>
</dependency>
Copy after login

GET request

public void httpclientGet() throws Exception{
 
  // 创建HttpClient对象
  HttpClient client = HttpClients.createDefault();
 
  // 创建GET请求(在构造器中传入URL字符串即可)
  HttpGet get = new HttpGet("http://127.0.0.1/http/demo.do?name=admin&age=40");
 
  // 调用HttpClient对象的execute方法获得响应
  HttpResponse response = client.execute(get);
 
  // 调用HttpResponse对象的getEntity方法得到响应实体
  HttpEntity httpEntity = response.getEntity();
 
  // 使用EntityUtils工具类得到响应的字符串表示
  String result = EntityUtils.toString(httpEntity,"utf-8");
  System.out.println(result);
}
Copy after login

Detailed explanation of http communication using JAVA

POST request

public void httpclientPost() throws Exception{
 
  // 创建HttpClient对象
  HttpClient client = HttpClients.createDefault();
 
  // 创建POST请求
  HttpPost post = new HttpPost("http://127.0.0.1/http/demo.do");
 
  // 创建一个List容器,用于存放基本键值对(基本键值对即:参数名-参数值)
  List<BasicNameValuePair> parameters = new ArrayList<>();
  parameters.add(new BasicNameValuePair("name", "张三"));
  parameters.add(new BasicNameValuePair("age", "25"));
 
  // 向POST请求中添加消息实体
  post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));
 
  // 得到响应并转化成字符串
  HttpResponse response = client.execute(post);
  HttpEntity httpEntity = response.getEntity();
  String result = EntityUtils.toString(httpEntity,"utf-8");
  System.out.println(result);
}
Copy after login

Detailed explanation of http communication using JAVA

HttpClient is a sub-project under Apache Jakarta Common, used to Provides an efficient, up-to-date, feature-rich client programming toolkit that supports the HTTP protocol, and it supports the latest version and recommendations of the HTTP protocol. HttpClient has been used in many projects. For example, two other famous open source projects on Apache Jakarta, Cactus and HTMLUnit, both use HttpClient.

For more detailed explanations of using JAVA to implement http communication, please pay attention to the PHP Chinese website!

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

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1676
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

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

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

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

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

See all articles