Unirest: A Java HTTP Request Courier!

Niuke’s Java Kitchen: Unirest, A Java HTTP Request Courier!

Opening Story

Hey friends, today I want to talk to you about HTTP requests! Do you remember when I first transitioned to Java development? I struggled to write the interface calling code and had to read the HttpURLConnection documentation three times just to piece together some code that worked! It was such a headache! Later, I discovered the “courier” of the Java world—Unirest. It’s simply a magic tool for writing HTTP requests, saving time, effort, and being highly efficient!

Today, let’s learn about this super tool together! We will use the analogy of cooking in the kitchen, comparing HTTP requests to “ordering takeout”, from placing the order, delivery to receiving it! After reading this article, you will be able to quickly write elegant HTTP request code without any pitfalls! Interested friends, hop on board!

Overview of Key Points

  • What is Unirest?
  • How to send HTTP requests with Unirest?
  • Basic code examples and detailed comments
  • Common pitfalls and solutions—Niuke’s pitfall diary
  • Practical: Calling a public API
  • Interviewer’s favorite question: “HTTP library comparison”
  • Performance optimization and debugging tips

Expected Learning Outcomes:

Through this article, we will master the basic usage of Unirest, learn to send HTTP requests elegantly, and understand its usage scenarios in real projects, making your code more concise and efficient!

1. What is Unirest?

Let’s start with the “kitchen cooking” analogy. Imagine that initiating an HTTP request is like ordering takeout. You need to tell the restaurant:

  • Order Details (Request method, URL, headers, body)
  • Delivery Method (Synchronous/Asynchronous)
  • Delivery Address (Data processing)

Here, HttpURLConnection is like an inefficient delivery person; you have to manually call, confirm every detail, and even follow up on the order yourself! How troublesome!

In contrast, Unirest is like an efficient takeout platform that wraps up all these tedious operations for you. You just need to fill out the order, and it can quickly handle everything! Unirest is a lightweight HTTP request library that supports both synchronous and asynchronous calls, is easy to use, and is perfect for beginners.

2. Environment Setup

Before we start working in our “kitchen”, we need to prepare the “ingredients”, right? The same goes for using Unirest; we need to set up the development environment first!

Configuration Steps:

  1. Make sure you are using JDK 8 or above.

  2. Add Unirest’s Maven dependency:

    xml copy

    <dependency>
        <groupId>com.konghq</groupId>
        <artifactId>unirest-java</artifactId>
        <version>3.13.12</version>
    </dependency>
    
    
  3. If using Gradle, add:

    groovy copy

    implementation 'com.konghq:unirest-java:3.13.12'
    
    
  4. Once installed, we can get started!

3. Basic Usage of Unirest

3.1 GET Request — Query Menu

A GET request is like “querying the menu”; you just need to tell the restaurant what you want to see, and they will return the corresponding menu data. Implementing this with Unirest is very simple:

java copy

import kong.unirest.HttpResponse;
import kong.unirest.JsonNode;
import kong.unirest.Unirest;

public class UnirestDemo {
    public static void main(String[] args) {
        // Send a GET request
        HttpResponse<JsonNode> response = Unirest.get("https://jsonplaceholder.typicode.com/posts/1")
                .header("accept", "application/json")
                .asJson();

        // Print the return result
        System.out.println("Status Code: " + response.getStatus());
        System.out.println("Response Data: " + response.getBody());
    }
}

Code Explanation:

  1. Unirest.get(url): Initiates a GET request.
  2. .header(key, value): Sets the request header.
  3. .asJson(): Parses the response directly into JSON format.
  4. response.getStatus(): Gets the HTTP status code.
  5. response.getBody(): Gets the response body data.

Running result:

plaintext copy

Status Code: 200
Response Data: {
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur..."
}

See, isn’t it a one-stop service that easily gets it done?

3.2 POST Request — Submit Order

A POST request is like “submitting an order”; you need to tell the restaurant the order details (request body).

Example:

java copy

HttpResponse<JsonNode> response = Unirest.post("https://jsonplaceholder.typicode.com/posts")
        .header("Content-Type", "application/json")
        .body("{\"title\":\"Niuke's Order\",\"body\":\"I want fried chicken and milk tea\",\"userId\":1}")
        .asJson();

System.out.println("Order submitted successfully! Status Code: " + response.getStatus());
System.out.println("Return Result: " + response.getBody());

Running result:

plaintext copy

Order submitted successfully! Status Code: 201
Return Result: {
  "id": 101,
  "title": "Niuke's Order",
  "body": "I want fried chicken and milk tea",
  "userId": 1
}

Tips:

  • POST requests are mainly used to send data; you can directly pass a JSON string in the body method.
  • Don’t forget to set Content-Type to application/json.

4. Niuke’s Pitfall Diary

Pitfall 1: Timeout Issues

Sometimes the interface response is too slow, which can hang the program. Unirest provides timeout settings:

java copy

Unirest.config().socketTimeout(5000).connectTimeout(5000);

In this way, if it exceeds 5 seconds, a timeout exception will be thrown, and we can choose to retry or prompt the user based on the needs!

Pitfall 2: Callback Hell of Asynchronous Calls

Unirest supports asynchronous calls, but callback hell can make the code messy! It is recommended to use CompletableFuture more, for example:

java copy

Unirest.get("https://jsonplaceholder.typicode.com/posts/1")
        .asJsonAsync(response -> {
            System.out.println("Asynchronous Response Data: " + response.getBody());
        });

5. Practical Project: Calling Weather API

We will use Unirest to call a public weather API to get the current weather information.

Code Example:

java copy

import kong.unirest.HttpResponse;
import kong.unirest.JsonNode;
import kong.unirest.Unirest;

public class WeatherApp {
    public static void main(String[] args) {
        String apiKey = "your_api_key"; // Replace with a real API Key
        String city = "Beijing";

        HttpResponse<JsonNode> response = Unirest.get("http://api.weatherapi.com/v1/current.json")
                .queryString("key", apiKey)
                .queryString("q", city)
                .asJson();

        if (response.getStatus() == 200) {
            System.out.println("Current Weather: " + response.getBody().getObject().getJSONObject("current"));
        } else {
            System.out.println("Failed to get weather!");
        }
    }
}

6. Interviewer’s Favorite Question: Unirest vs HttpClient

Feature Unirest HttpClient
Ease of Use ⭐⭐⭐⭐⭐ ⭐⭐⭐
Supports Asynchronous
Customization Ability ⭐⭐⭐ ⭐⭐⭐⭐⭐
Community Support ⭐⭐⭐⭐ ⭐⭐⭐⭐⭐

Interview Tips: Unirest is more suitable for rapid development, while HttpClient excels in flexibility and scalability.

Conclusion

Friends, today’s learning about Unirest ends here! We easily achieved GET and POST requests, encountered a few pitfalls, and finally did a practical project of querying the weather.

Project Assignment:

  1. Use Unirest to call a movie API to get a list of popular movies.
  2. Consider: If the API returns a large amount of data, how to optimize?

If you have any questions, feel free to ask me in the comments, and let’s grow together! I wish you all happy learning and a great journey in Java! 🚀

Leave a Comment