杰瑞科技汇

Java HttpService如何实现高效通信?

Of course! The term "Java HTTP Service" can refer to two main things, which is a common point of confusion:

Java HttpService如何实现高效通信?-图1
(图片来源网络,侵删)
  1. A Java Client that makes HTTP requests (e.g., calling a REST API).
  2. A Java Server that receives HTTP requests (e.g., creating a REST API).

I'll cover both, starting with the most common modern approaches.


Java HTTP Client (Making HTTP Requests)

This is about your Java application acting as a client to consume web services or APIs.

Modern Standard: java.net.http (Java 11+)

Since Java 11, the java.net.http package provides a modern, built-in, and non-blocking HTTP client. This is the recommended approach for new projects.

Key Features:

Java HttpService如何实现高效通信?-图2
(图片来源网络,侵删)
  • Built into the JDK.
  • Supports both HTTP/1.1 and HTTP/2.
  • Supports asynchronous (non-blocking) requests.
  • Supports WebSocket.
  • Fluent and easy-to-use API.

Example: Making a GET Request

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 JavaHttpClientExample {
    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))
                .build();
        // 2. Create an HttpRequest
        HttpRequest request = HttpRequest.newBuilder()
                .GET() // GET is the default
                .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
                .header("Accept", "application/json")
                .build();
        try {
            // 3. Send the request and get the response
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            // 4. Process the response
            System.out.println("Status Code: " + response.statusCode());
            System.out.println("Response Body:");
            System.out.println(response.body());
        } catch (Exception e) {
            System.err.println("Request failed: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Example: Making a POST Request (with JSON body)

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;
import java.time.Duration;
import java.util.Map;
public class JavaHttpPostExample {
    public static void main(String[] args) {
        HttpClient client = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_2)
                .connectTimeout(Duration.ofSeconds(10))
                .build();
        // JSON payload for the new post
        String jsonPayload = "{ \"title\": \"foo\", \"body\": \"bar\", \"userId\": 1 }";
        HttpRequest request = HttpRequest.newBuilder()
                .POST(BodyPublishers.ofString(jsonPayload))
                .uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
                .header("Content-Type", "application/json")
                .header("Accept", "application/json")
                .build();
        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println("Status Code: " + response.statusCode());
            System.out.println("Response Body (New Post created with ID):");
            System.out.println(response.body());
        } catch (Exception e) {
            System.err.println("Request failed: " + e.getMessage());
        }
    }
}

Legacy Standard: HttpURLConnection (Java 1.1+)

Before Java 11, java.net.HttpURLConnection was the standard, built-in way. It's more verbose and less powerful than the modern client.

Characteristics:

Java HttpService如何实现高效通信?-图3
(图片来源网络,侵删)
  • Part of the standard library since Java 1.1.
  • Synchronous (blocking) by default.
  • API can be clunky (e.g., manually handling streams, setting request methods with setRequestMethod).

Example: GET Request with HttpURLConnection

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class LegacyHttpUrlConnectionExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://jsonplaceholder.typicode.com/posts/1");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // Set request method
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept", "application/json");
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                // print result
                System.out.println("Response Body:");
                System.out.println(response.toString());
            } else {
                System.out.println("GET request failed");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Popular Third-Party Libraries

For more complex needs or projects on older Java versions, these libraries are extremely popular.

  • Apache HttpComponents (HttpClient): A very powerful, mature, and feature-rich library. It's the go-to for many enterprise applications. It has a steeper learning curve but offers immense flexibility.
  • OkHttp: A modern, efficient HTTP client for Android and Java. It's known for its ease of use, connection pooling, and transparent GZIP. It's a great choice if you can add a third-party dependency.
  • RestTemplate (Spring Framework): If you are using the Spring framework, RestTemplate is the classic, synchronous client for making HTTP requests. It's simple but has been superseded by WebClient for new reactive applications.

Java HTTP Server (Receiving HTTP Requests)

This is about your Java application exposing an HTTP endpoint, like a REST API or a simple web server.

Simple Built-in Server: com.sun.net.httpserver (Not for Production)

JDK includes a simple HTTP server implementation in the com.sun.net.httpserver package. It's great for quick demos, testing, or simple internal tools but is not recommended for production use due to lack of features (security, scalability, etc.).

Example: A Simple "Hello World" Server

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 SimpleHttpServerExample {
    public static void main(String[] args) throws IOException {
        // Create the server on port 8080
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        // Create a context for the "/hello" endpoint
        server.createContext("/hello", new HelloHandler());
        // Set the executor (optional, but good practice)
        server.setExecutor(null); // creates a default executor
        // Start the server
        server.start();
        System.out.println("Server started on port 8080. Access /hello");
    }
    static class HelloHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            // Determine the request method
            if ("GET".equals(exchange.getRequestMethod())) {
                String response = "Hello, World! This is a response from the Java HTTP Server.";
                exchange.sendResponseHeaders(200, response.length()); // 200 OK
                OutputStream os = exchange.getResponseBody();
                os.write(response.getBytes());
                os.close();
            } else {
                // Method not allowed
                String response = "Method not allowed";
                exchange.sendResponseHeaders(405, response.length()); // 405 Method Not Allowed
                OutputStream os = exchange.getResponseBody();
                os.write(response.getBytes());
                os.close();
            }
        }
    }
}

Run this and then open your browser or use curl http://localhost:8080/hello.


Production-Grade Frameworks

For any real-world application, you should use a dedicated web framework. They handle routing, security, templating, database connections, and much more.

  • Spring Boot: The dominant framework in the Java ecosystem. It makes incredibly easy to build production-ready web applications and REST APIs. It uses an embedded server (like Tomcat or Jetty) by default.
  • Jakarta EE (formerly Java EE): The standard for enterprise Java. It includes Jakarta Servlet API (the foundation for all Java web servers) and Jakarta RESTful Web Services (JAX-RS) for building APIs. Servers like Payara, WildFly, and Tomcat implement these standards.
  • Micronaut: A modern, lightweight framework designed for serverless, cloud-native, and microservices architectures. It has very fast startup times and low memory footprint.
  • Quarkus: Another modern, Kubernetes-native Java stack tailored for GraalVM and OpenJDK HotSpot. It's designed for containers and offers exceptional performance and memory efficiency.

Example: A REST Controller with Spring Boot

This is the most common way to create an HTTP service in Java today.

  1. Add Spring Boot Starter Web dependency to your pom.xml:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  2. Create a controller class:

    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    @RestController // Marks this class as a controller where every method returns a domain object instead of a view
    @RequestMapping("/api") // Base path for all endpoints in this controller
    public class GreetingController {
        @GetMapping("/greeting") // Maps GET requests for "/api/greeting" to this method
        public String greeting() {
            return "Hello, from a Spring Boot REST Service!";
        }
    }
  3. Run your Spring Boot application. It will automatically start a web server (e.g., Tomcat) on port 8080. You can now access http://localhost:8080/api/greeting in your browser or via an API client.

Summary Table

Type Technology/Library When to Use
HTTP Client java.net.http (Java 11+) Recommended for new projects. Modern, built-in, supports async/HTTP2.
HTTP Client HttpURLConnection (Legacy) For very simple tasks on older Java versions (<11) or when you cannot add third-party dependencies.
HTTP Client Apache HttpComponents / OkHttp When you need advanced features, better API, or are on a project that already uses them.
HTTP Server com.sun.net.httpserver For quick demos, tests, or simple internal tools. Avoid for production.
HTTP Server (API) Spring Boot / Micronaut / Quarkus Recommended for all production applications. They provide a complete, secure, and scalable framework.
HTTP Server (API) Jakarta EE / JAX-RS For building standard-compliant enterprise applications, especially if you're in a Java EE environment.
分享:
扫描分享到社交APP
上一篇
下一篇