杰瑞科技汇

HttpClient Java Jar 如何正确使用?

Of course! This is a very common topic for Java developers. The term "httpclient java jar" usually refers to one of two things:

HttpClient Java Jar 如何正确使用?-图1
(图片来源网络,侵删)
  1. The modern, standard java.net.http.HttpClient (Java 11+): This is now built directly into the Java Development Kit (JDK). You don't need to add any external JAR files to your project for this.
  2. The legacy Apache HttpClient: This is a very popular, third-party library that was the de-facto standard before Java 11. You do need to add its JAR files to your project.

Let's break down both.


The Modern java.net.http.HttpClient (Recommended for Java 11+)

This is the standard, modern way to make HTTP requests in Java. It's part of the Java Standard Library, which means it's robust, well-maintained by Oracle, and doesn't require any external dependencies.

How to Use It (No JARs needed)

Since it's built-in, you just need to write the code.

Example: Making a GET Request

HttpClient Java Jar 如何正确使用?-图2
(图片来源网络,侵删)
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class ModernHttpClientExample {
    public static void main(String[] args) {
        // 1. Create an HttpClient
        HttpClient client = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_2)
                .connectTimeout(Duration.ofSeconds(10))
                .build();
        // 2. Create an HttpRequest
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.github.com/users/octocat"))
                .header("Accept", "application/vnd.github.v3+json")
                .GET() // This is the default, but explicit is good
                .build();
        try {
            // 3. Send the request and get the response
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            // 4. Print the results
            System.out.println("Status Code: " + response.statusCode());
            System.out.println("Response Body:");
            System.out.println(response.body());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Key Features:

  • Asynchronous Support: It has a powerful, non-blocking API for asynchronous requests.
  • HTTP/2 Support: Full support for the latest HTTP protocol.
  • Fluent API: Easy-to-use builder pattern for creating clients and requests.
  • No Dependencies: Just works out of the box with any modern JDK.

The Legacy Apache HttpClient (For older projects or specific needs)

Apache HttpClient is a mature, feature-rich library that was extremely popular before Java 11. You might need it if you're working on a project with an older Java version (Java 8 or earlier) or if you need features not yet available in the standard library.

How to Use It (Requires JARs)

You need to add the Apache HttpClient dependencies to your project.

Step 1: Add Dependencies to Your Project

Using Maven (pom.xml)

Add this to your <dependencies> section:

HttpClient Java Jar 如何正确使用?-图3
(图片来源网络,侵删)
<dependencies>
    <!-- Core HttpClient library -->
    <dependency>
        <groupId>org.apache.httpcomponents.client5</groupId>
        <artifactId>httpclient5</artifactId>
        <version>5.3.1</version> <!-- Use the latest version -->
    </dependency>
    <!-- Required for connection pooling and other features -->
    <dependency>
        <groupId>org.apache.httpcomponents.core5</groupId>
        <artifactId>httpcore5</artifactId>
        <version>5.2.4</version> <!-- Use the latest version -->
    </dependency>
    <!-- For JSON handling (very common) -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.16.1</version> <!-- Use the latest version -->
    </dependency>
</dependencies>

Using Gradle (build.gradle)

Add this to your dependencies block:

dependencies {
    // Core HttpClient library
    implementation 'org.apache.httpcomponents.client5:httpclient5:5.3.1' // Use the latest version
    // Required for connection pooling and other features
    implementation 'org.apache.httpcomponents.core5:httpcore5:5.2.4' // Use the latest version
    // For JSON handling (very common)
    implementation 'com.fasterxml.jackson.core:jackson-databind:2.16.1' // Use the latest version
}

Step 2: Write the Code

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.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
public class ApacheHttpClientExample {
    public static void main(String[] args) {
        // 1. Create a HttpClient instance
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 2. Create an HttpGet request
            HttpGet request = new HttpGet("https://api.github.com/users/octocat");
            request.addHeader("Accept", "application/vnd.github.v3+json");
            // 3. Execute the request
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                // 4. Get the response entity
                HttpEntity entity = response.getEntity();
                // 5. Process the response
                if (entity != null) {
                    String result = EntityUtils.toString(entity);
                    System.out.println("Status Code: " + response.getCode());
                    System.out.println("Response Body:");
                    System.out.println(result);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Key Features:

  • Highly Customizable: Extremely flexible with connection management, cookie handling, authentication, and more.
  • Mature and Stable: Has been around for a long time and is battle-tested.
  • Backward Compatibility: Works on older Java versions.
  • Large Ecosystem: Integrates well with many other Apache projects.

Summary: Which One Should You Use?

Feature java.net.http.HttpClient (Java 11+) Apache HttpClient
Dependency None (Built into JDK) Required (Maven/Gradle)
Java Version Java 11 or later Java 6+ (but 5.x requires Java 8+)
Ease of Use Very easy, fluent API Easy, but more verbose
Features Excellent core features (HTTP/2, async) Extremely feature-rich and customizable
Recommendation Use for all new projects on Java 11+. Use for legacy projects or when you need specific advanced features not in the standard library.

Final Recommendation: If you are starting a new project and your environment supports Java 11 or newer, you should absolutely use the built-in java.net.http.HttpClient. It's the future of HTTP in Java and is simpler to manage. Only reach for Apache HttpClient if you have a specific, compelling reason to do so.

分享:
扫描分享到社交APP
上一篇
下一篇