Brother Niu’s Java Kitchen: Apache HttpClient, The Messenger of Network Requests!
Today, let’s talk about an interesting and practical tool – Apache HttpClient! This tool is like the “SF Express” of network requests, helping us deliver information far and wide, and even receive the recipient’s “delivery receipt” (response result). As a programmer who transitioned from testing to Java development, I was completely confused when I first encountered HttpClient: what are request headers, response bodies, connection pools… it made my head spin! However, after stumbling through it, I finally grasped its essence.
Today, we will take a look at how this “delivery guy” works! Don’t worry, we’ll discuss it from the perspective of cooking in the kitchen, making it easy to learn! The article will also include my personal experiences of stumbling through, code optimization tips, and tricky questions that interviewers love to ask, so make sure to read to the end!
1. Kitchen Warm-up: The Uses of Apache HttpClient
Let’s start with a real-life scenario: Imagine one day you are cooking at home and suddenly realize you are out of salt! So you quickly take out your phone, open a shopping app, and order some salt. At this moment, your app sends a network request to convey the salt order information to the backend server, which arranges for delivery once it receives the order. When the delivery person brings the salt, you confirm receipt, completing the entire process.
In programming, Apache HttpClient is the courier responsible for “sending requests” and “receiving responses”! It allows you to easily handle various network operations, such as:
- Sending HTTP requests: It handles common operations like GET, POST, PUT, DELETE!
- Receiving server responses: For example, checking the content and status code returned by the interface.
- Handling complex scenarios: It supports HTTPS, retry mechanisms, connection pool optimizations, etc.
2. Preparing Tools: Kitchen Environment Setup
To make a “network feast” with HttpClient, we need to prepare our tools first. Here are the specific steps:
1. Add Dependencies
If your project uses Maven
, simply add the following dependency in your pom.xml
:
xml copy
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2</version>
</dependency>
2. Import Necessary Packages
Make sure you import the following classes:
java copy
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.sync.HttpClients;
import org.apache.hc.core5.http.io.entity.StringEntity;
Alright, the tools are ready, and we can officially start working!
3. Basic Operations: Making a Bowl of “GET Request Noodles”
1. Basic Code Example
First, let’s use a GET request to access a simple interface, such as https://jsonplaceholder.typicode.com/posts, to retrieve a set of article data.
java copy
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.sync.HttpClients;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpClientDemo {
public static void main(String[] args) {
// Create HttpClient object
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// Create GET request
HttpGet request = new HttpGet("https://jsonplaceholder.typicode.com/posts");
// Send request and receive response
try (CloseableHttpResponse response = httpClient.execute(request)) {
// Output status code
System.out.println("Status Code: " + response.getCode());
// Read response content
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
} catch (Exception e) {
System.out.println("Request Error: " + e.getMessage());
}
}
}
2. Code Annotations
CloseableHttpClient
: This is our chef, responsible for executing HTTP requests.HttpGet
: GET request, like the instruction “go to the supermarket to buy something”.BufferedReader
: Reads the response content line by line, just like putting the groceries into the fridge.
3. Running Effect
After running, the program will print the status code 200
(indicating the request was successful) and a bunch of article data. The GET request noodles are ready!
4. Advanced Operations: POST Request “Braised Pork”
GET requests can only retrieve data; what if you want to upload data? For example, if you want to upload a “Braised Pork” recipe to a food sharing platform, you need to use a POST request!
POST Request Example Code
java copy
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.sync.HttpClients;
import org.apache.hc.core5.http.io.entity.StringEntity;
public class HttpClientDemo {
public static void main(String[] args) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// Create POST request
HttpPost post = new HttpPost("https://jsonplaceholder.typicode.com/posts");
// Set request body
String json = "{\"title\":\"Braised Pork\",\"body\":\"Delicious and not greasy\",\"userId\":1}";
post.setEntity(new StringEntity(json));
post.setHeader("Content-Type", "application/json");
// Send request and receive response
try (CloseableHttpResponse response = httpClient.execute(post)) {
System.out.println("Status Code: " + response.getCode());
System.out.println("Response Content: " + response.getEntity().getContent().toString());
}
} catch (Exception e) {
System.out.println("Request Error: " + e.getMessage());
}
}
}
5. Brother Niu’s Pitfall Diary
- Forgetting to Close Resources: HttpClient is a closable resource; forgetting to call
close()
can lead to memory leaks. It’s recommended to usetry-with-resources
! - Request Timeout Issues: The default timeout may not be sufficient, so remember to manually set timeout parameters.
- HTTPS Errors: When accessing HTTPS interfaces, improper certificate configuration may cause errors, so check the certificate issues.
6. Code Optimization Clinic
- Use Connection Pooling: Frequently creating HttpClient objects can degrade performance; use
PoolingHttpClientConnectionManager
for optimization. - Set Global Timeout: To avoid requests hanging, for example: java copy
RequestConfig config = RequestConfig.custom() .setConnectTimeout(5000) // Connection timeout .setResponseTimeout(5000) // Response timeout .build(); CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
7. Interviewer’s Favorite Questions
-
What is the difference between HttpClient and HttpURLConnection?
- HttpClient is more powerful, supporting connection pooling and retry mechanisms, while HttpURLConnection is lighter but has limited functionality.
-
How to handle concurrent requests?
- Use connection pooling to optimize and reuse existing connections for each request.
8. Conclusion
Today, we learned the basic operations of Apache HttpClient, from GET request noodles to POST request braised pork, and shared my experiences of stumbling through and optimization tips! Your task today is: use HttpClient to implement a simple weather query program that prints the weather information of a city.
If you have any questions, feel free to ask me in the comments! Remember to practice more; the world of network programming is waiting for you to explore! Keep it up, and see you next time!