杰瑞科技汇

httpservice java 是什么?

Of course! Let's break down HttpService in Java. It's a broad term, so I'll cover the three most common meanings you'll encounter:

httpservice java 是什么?-图1
(图片来源网络,侵删)
  1. The Modern Way (Java 11+): The java.net.http.HttpClient API - This is the current, recommended standard for making HTTP requests in Java.
  2. The Classic Way (Legacy): The Apache HttpComponents HttpClient - A very powerful and widely used third-party library that was the de-facto standard before Java 11.
  3. The Server-Side Way: Creating an HTTP Server - Using Java to build a service that receives HTTP requests.

The Modern Way: java.net.http.HttpClient (Java 11+)

This is the built-in, standard HTTP client introduced in Java 11. It's modern, supports HTTP/2, asynchronous requests, and a clean, fluent API.

Key Concepts

  • HttpClient: The main entry point. You create an instance and configure it (e.g., whether to follow redirects, use a proxy).
  • HttpRequest: Represents the request you want to send. You specify the URI, method (GET, POST, etc.), headers, and a body.
  • HttpResponse<T>: Represents the response you receive. The type T is a "response body handler" that dictates how the body is processed (e.g., as a String, byte[], or even streamed).

Example: Making a GET Request

This example fetches the content of a JSON API and prints it as a String.

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) // Use HTTP/2 if possible
                .connectTimeout(Duration.ofSeconds(10)) // Set a timeout
                .build();
        // 2. Create an HttpRequest
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://jsonplaceholder.typicode.com/todos/1"))
                .header("Accept", "application/json") // Set a header
                .GET() // GET is the default, but it's good to be explicit
                .build();
        try {
            // 3. Send the request and get the response
            // The response body is handled as a String
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            // 4. Check the status code and print the body
            System.out.println("Status Code: " + response.statusCode());
            if (response.statusCode() == 200) {
                System.out.println("Response Body:");
                System.out.println(response.body());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Example: Making an Asynchronous POST Request

This example sends JSON data in a POST request without blocking the main thread.

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
public class AsyncPostExample {
    public static void main(String[] args) {
        HttpClient client = HttpClient.newHttpClient();
        String jsonBody = """
            {
              "title": "foo",
              "body": "bar",
              "userId": 1
            }
            """;
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
                .build();
        // Send the request asynchronously
        CompletableFuture<HttpResponse<String>> futureResponse = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
        // Define what to do when the response is received
        futureResponse.thenAccept(response -> {
            System.out.println("Async Response Status: " + response.statusCode());
            System.out.println("Async Response Body: " + response.body());
        }).exceptionally(e -> {
            System.err.println("Request failed: " + e.getMessage());
            return null; // Required for CompletableFuture chain
        });
        System.out.println("Request sent! Main thread is not blocked.");
        // Wait for the asynchronous operation to complete (otherwise the program might exit)
        futureResponse.join();
    }
}

The Classic Way: Apache HttpComponents

Before Java 11, this was the most robust and feature-rich HTTP client. It's still widely used in many enterprise applications, especially those running on older Java versions.

httpservice java 是什么?-图2
(图片来源网络,侵删)

You need to add the dependency to your project (e.g., in Maven):

<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.3.1</version> <!-- Use the latest version -->
</dependency>

Example: Making a GET Request

This example does the same thing as the first HttpClient example but using Apache's API.

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.io.entity.EntityUtils;
import org.apache.hc.core5.net.URIBuilder;
public class ApacheHttpClientExample {
    public static void main(String[] args) {
        // 1. Create a HttpClient instance
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 2. Create an HttpGet request
            // URIBuilder helps with encoding parameters
            HttpGet request = new HttpGet("https://jsonplaceholder.typicode.com/todos/1");
            // 3. Execute the request
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                // 4. Get the response entity and print it
                String responseBody = EntityUtils.toString(response.getEntity());
                System.out.println("Status Code: " + response.getCode());
                System.out.println("Response Body:");
                System.out.println(responseBody);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The Server-Side Way: Creating an HTTP Service

If you mean creating a service that listens for HTTP requests, you have several options in Java.

Option A: The Simple com.sun.net.httpserver (Java 6+)

This is a built-in, lightweight HTTP server. It's great for simple tools, testing, or internal services, but not for production-grade web applications.

httpservice java 是什么?-图3
(图片来源网络,侵删)
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
public class SimpleHttpServer {
    public static void main(String[] args) throws IOException {
        // 1. Create the server on port 8080
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        // 2. Create a context (a path) and assign a handler to it
        server.createContext("/hello", new MyHandler());
        // 3. Set the executor (optional, but good for handling multiple requests)
        server.setExecutor(null); // creates a default executor
        // 4. Start the server
        server.start();
        System.out.println("Server started on port 8080. Visit http://localhost:8080/hello");
    }
    // 5. Define the handler
    static class MyHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            // We only handle GET requests for this example
            if ("GET".equals(exchange.getRequestMethod())) {
                String response = "Hello from the Java HTTP Server!";
                // Set the response headers
                exchange.getResponseHeaders().set("Content-Type", "text/plain");
                exchange.sendResponseHeaders(200, response.getBytes().length);
                // Write the response body
                try (OutputStream os = exchange.getResponseBody()) {
                    os.write(response.getBytes());
                }
            } else {
                // Handle other methods (e.g., 405 Method Not Allowed)
                String response = "Method Not Allowed";
                exchange.sendResponseHeaders(405, response.getBytes().length);
                try (OutputStream os = exchange.getResponseBody()) {
                    os.write(response.getBytes());
                }
            }
        }
    }
}

Option B: Production-Grade Frameworks (Spring Boot, Jakarta EE)

For building real-world web services (REST APIs, web applications), you use a full-featured framework like Spring Boot. It handles all the low-level server setup, routing, request parsing, and much more.

Here's a tiny taste of what a Spring Boot controller looks like:

// This is a Spring Boot @RestController
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MySpringController {
    // This method handles GET requests to "/greeting"
    @GetMapping("/greeting")
    public String greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
        return "Hello, " + name + "!";
    }
}

When you run this Spring Boot application, it automatically starts a server (like Tomcat), and you can access http://localhost:8080/greeting or http://localhost:8080/greeting?name=Java.


Summary: Which One Should I Use?

Scenario Recommended Tool Why?
Making HTTP requests in a modern Java 11+ application java.net.http.HttpClient It's the standard, built-in, modern API. No dependencies needed.
Making HTTP requests in an older Java project (pre-11) Apache HttpComponents It's the most robust, feature-rich, and reliable third-party library.
Creating a simple, internal HTTP server for testing or a tool com.sun.net.httpserver Lightweight, built-in, and easy to set up for basic needs.
Building a production-grade web service or REST API Spring Boot / Jakarta EE Provides a complete ecosystem for building scalable, maintainable applications.
分享:
扫描分享到社交APP
上一篇
下一篇