Apache HttpClient: The Java Network Request Courier

Apache HttpClient – The Java Network Request Courier

Hello everyone, I am Niu Ge, transitioning from testing to Java! Today, we are going to talk about the “courier” in Java – Apache HttpClient. I still remember the first project I took on after transitioning, which required calling several external APIs. At that time, I was confused: how do you send HTTP requests in Java?

Don’t worry, today Niu Ge will guide you to learn about this “universal courier” in Java. After learning this, you will be able to easily perform API calls, data scraping, and more!

First Experience with the Courier

Imagine this: you place an order on an e-commerce platform, and the courier delivers your package. Isn’t that just like an HTTP request?

  • You (the client) send a request to the merchant (the server)
  • The courier (HttpClient) is responsible for delivering your package (data)
  • The merchant processes it and returns the result (response)

Let’s see how to use this courier:

java copy

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClientDemo {
    public static void main(String[] args) {
        // 1. Hire a courier
        CloseableHttpClient httpClient = HttpClients.createDefault();
        
        try {
            // 2. Prepare the delivery order (GET request)
            HttpGet httpGet = new HttpGet("https://api.example.com/data");
            
            // 3. Send the delivery
            CloseableHttpResponse response = httpClient.execute(httpGet);
            
            try {
                // 4. Check the delivery result
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println("Received response: " + result);
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 5. Time to go home
            try {
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Would you like me to explain or break down the code?

Niu Ge’s Pitfall Diary

Attention everyone! There are a few pitfalls I fell into:

  1. Don’t forget to close the response and the client, or it will cause memory leaks
  2. Remember to handle various exceptions; network requests are prone to issues
  3. Chinese garbled text issue; set the correct encoding format

POST Request: Sending Large Packages

Sometimes we need to send data to the server, just like filling out package information when sending a courier:

java copy

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;

public class PostDemo {
    public static void main(String[] args) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        
        try {
            HttpPost httpPost = new HttpPost("https://api.example.com/submit");
            
            // Prepare package content
            String json = "{\"name\":\"Niu Ge\",\"message\":\"Hello\"}";
            StringEntity entity = new StringEntity(json);
            entity.setContentType("application/json");
            
            httpPost.setEntity(entity);
            
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // ... Handle response ...
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Would you like me to explain or break down the code?

Practical Tips

  1. Set a timeout to avoid requests hanging indefinitely
  2. Use connection pooling to enhance performance
  3. Add a retry mechanism to handle temporary network issues
  4. Use logging to record request/response information

Common Interview Questions

  • What is the difference between HttpClient and the native URLConnection?
  • How to handle HTTPS requests?
  • What is the role of connection pooling and how to configure it?
  • How to set proxies and handle certificate issues?

Practical Project Assignment

Everyone, here’s a small task:

  1. Write a program to scrape the titles of a news website
  2. Implement a weather query API call
  3. Add retry and timeout mechanisms to the code

Summary & Expansion

Today we learned:

  • The basic usage of HttpClient
  • Sending GET/POST requests
  • Response handling and exception handling
  • Performance optimization techniques

For those who want to dive deeper, you can check these out:

  • Using RestTemplate
  • Features of OkHttp
  • WebClient reactive programming

Everyone, today’s Java network courier training ends here! Remember to practice, and feel free to ask Niu Ge any questions in the comment section. This knowledge is particularly useful in actual projects, so make sure to master it! I look forward to seeing your code shares in the comments, let’s improve together!

Preview

In the next episode, we will learn “Spring Boot – The Ready-to-Use Java Full-Stack Kitchen”, so stay tuned! Your likes are the motivation for Niu Ge to update!

Leave a Comment