杰瑞科技汇

Java XMLHttpRequest 如何跨域请求?

Of course! Let's dive into XMLHttpRequest in Java.

Java XMLHttpRequest 如何跨域请求?-图1
(图片来源网络,侵删)

This is a very common point of confusion because the name XMLHttpRequest is most famously associated with JavaScript in web browsers. In Java, you don't use the exact same object, but you use the same underlying concept and protocol to make HTTP requests.

Here's a breakdown:

  1. The Core Concept: What XMLHttpRequest does.
  2. The Java Equivalents: The standard libraries in Java to achieve this.
  3. Code Examples: Simple, practical examples using the most common Java library.
  4. Comparison: HttpURLConnection vs. modern third-party libraries.

The Core Concept: What is XMLHttpRequest?

XMLHttpRequest (XHR) is an API in JavaScript that allows a web browser to communicate with a server after a page has loaded. This is the foundation of modern web applications, enabling features like:

  • AJAX (Asynchronous JavaScript and XML): Updating parts of a web page without reloading the whole thing.
  • Fetching data from a server in the background.
  • Sending data to a server (e.g., submitting a form).

In essence, it's a tool for making HTTP requests (GET, POST, PUT, DELETE, etc.) from a client to a server.

Java XMLHttpRequest 如何跨域请求?-图2
(图片来源网络,侵删)

The Java Equivalents

In Java, you are typically writing a server-side application (e.g., with Spring Boot) or a standalone command-line tool. You need a way for your Java code to act as a client and make HTTP requests. Java provides several ways to do this, ranging from built-in libraries to powerful third-party ones.

Here are the main options:

Method Pros Cons Best For
java.net.HttpURLConnection - Built into Java (no dependencies)
- Simple for basic GET/POST requests
- Verbose and clunky API
- Lacks modern features like connection pooling, JSON parsing, async support
Quick scripts, simple utilities, or when you cannot add external libraries.
HttpClient (Java 11+) - Modern, built-in API
- Supports HTTP/2
- Cleaner than HttpURLConnection
- Asynchronous support
- Still requires manual JSON handling (with libraries like Jackson or Gson) Modern Java applications (11+) that need a solid, standard HTTP client.
Third-Party Libraries (e.g., Apache HttpClient, OkHttp, Spring RestTemplate) - Extremely powerful and feature-rich
- Often include connection pooling, JSON/XML handling, retries, and easy async support
- Much more developer-friendly
- Adds an external dependency to your project Production applications, microservices, or any complex HTTP interaction.

Code Examples

Let's look at how to perform a GET request and a POST request with JSON data using the most common "from scratch" approach and then a popular library.

Example A: Using java.net.HttpURLConnection (The Built-in Way)

This is the most fundamental way. It's a bit verbose, but it's good to understand how it works under the hood.

Java XMLHttpRequest 如何跨域请求?-图3
(图片来源网络,侵删)

Simple GET Request

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionGetExample {
    public static void main(String[] args) {
        // The URL of the public API we are calling
        String apiUrl = "https://jsonplaceholder.typicode.com/posts/1";
        try {
            // 1. Create a URL object
            URL url = new URL(apiUrl);
            // 2. Open a connection to the URL
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 3. Set the request method
            connection.setRequestMethod("GET");
            // 4. Set request headers (optional)
            connection.setRequestProperty("User-Agent", "MyJavaApp/1.0");
            // 5. Get the response code
            int responseCode = connection.getResponseCode();
            System.out.println("Sending GET request to URL : " + apiUrl);
            System.out.println("Response Code : " + responseCode);
            // 6. Read the response
            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. Response Code: " + responseCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

POST Request with JSON

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class HttpURLConnectionPostExample {
    public static void main(String[] args) {
        String apiUrl = "https://jsonplaceholder.typicode.com/posts";
        String jsonInputString = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";
        try {
            URL url = new URL(apiUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true); // This is crucial for POST requests
            // Write the JSON data to the request body
            try(OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
            // Get the response
            int responseCode = connection.getResponseCode();
            System.out.println("Sending POST request to URL : " + apiUrl);
            System.out.println("Response Code : " + responseCode);
            // Read the response (similar to the GET example)
            // ... (code to read response stream) ...
            System.out.println("POST request successful.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Example B: Using a Third-Party Library (Apache HttpClient - Recommended)

This is the preferred method in most real-world Java projects. The API is much cleaner and more intuitive.

First, add the dependency to your pom.xml (Maven):

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

Simple GET Request with Apache HttpClient

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 ApacheHttpClientGetExample {
    public static void main(String[] args) {
        String apiUrl = "https://jsonplaceholder.typicode.com/posts/1";
        // Use try-with-resources to ensure the client is closed
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet request = new HttpGet(apiUrl);
            // Execute the request
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                // Get the response entity
                HttpEntity entity = response.getEntity();
                // Print the response status
                System.out.println("Response Code: " + response.getCode());
                if (entity != null) {
                    // Convert the response entity to a String and print it
                    String result = EntityUtils.toString(entity);
                    System.out.println("Response Body:");
                    System.out.println(result);
                    EntityUtils.consume(entity); // Ensure the content is fully consumed and the stream is closed
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Comparison: HttpURLConnection vs. Modern Libraries

Feature HttpURLConnection HttpClient (Java 11+) Apache HttpClient / OkHttp
Ease of Use Verbose, clunky Better, but still manual Excellent. Fluent, intuitive API.
JSON Handling Manual (need a separate library like Jackson/Gson) Manual (need a separate library like Jackson/Gson) Excellent. Often integrates seamlessly with Jackson/Gson.
Async Support Clunky, requires manual threading Built-in and clean Excellent. Easy-to-use async APIs.
Connection Pooling Manual management Built-in Excellent. Highly configurable and automatic.
Dependencies None (built-in) None (built-in) Requires adding a library (httpclient5, okhttp)
Recommendation For simple scripts only. A good modern standard, but still feels low-level. The industry standard for most serious Java
分享:
扫描分享到社交APP
上一篇
下一篇