overview

Overview

Origin

In the world of Java, the HttpClient from Apache used to dominate the Http client scene. However, due to its bulky size and difficult-to-use API, it is not suitable for many scenarios. While emerging alternatives like OkHttp and Jodd-http are user-friendly, they still have a learning curve for certain situations. Many times, we want a lightweight Http client that is simple and easy to use. The HttpUrlConnection provided by the JDK can meet most of our needs. Hutool provides a layer of encapsulation for this, making Http requests incredibly simple.

Introduction

Hutool-http provides a layer of encapsulation for the JDK’s HttpUrlConnection, simplifying operations like HTTPS requests, file uploads, and Cookie handling, making Http requests incredibly simple.

The core of Hutool-http is centered around two classes:

  • HttpRequest
  • HttpResponse

At the same time, Hutool-http encapsulates the HttpUtil utility class for most scenarios.

Advantages of Hutool-http

  1. Automatically determines whether to request HTTP or HTTPS based on the URL, without the need for extra code.
  2. Automatically converts form data containing File objects to multipart/form-data form, without the need for separate operations.
  3. Automatically records Cookies by default, allowing for simulated logins where subsequent requests are in a logged-in state after visiting the login URL once.
  4. Automatically identifies and handles 304 redirects with a second request.
  5. Automatically identifies and decodes page encodings based on header information or relevant tags in the page, minimizing the risk of encoding errors.
  6. Automatically identifies and decompresses Gzip-formatted returned content.

Usage

The simplest usage is to quickly request a page using the HttpUtil utility class:

// GET request
String content = HttpUtil.get(url);

A single line of code is all it takes. Similarly, POST requests are just as simple:

// POST request
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("city", "Beijing");

String result1 = HttpUtil.post(url, paramMap);

For POST requests, you can use a Map to specify form fields in advance.

More

According to Hutool’s principle of “convenience and flexibility coexisting,” the existence of HttpUtil embodies convenience, while the use of HttpRequest objects embodies flexibility. Using this object allows you to customize more attributes for the request to adapt to different scenarios in Http requests (such as custom headers, custom Cookies, custom proxies, etc.). Please refer to the following sections for usage of related classes.