Java 的 URL 类和 HttpURLConnection 类有什么作用?请举例说明如何通过它们发送 HTTP 请求并处理响应。

Java 中的 URL 类和 HttpURLConnection 类是用于处理网络请求的核心类,常用于发送 HTTP 请求并处理响应。以下是它们的详细介绍和示例说明:

URL 类的作用

URL 类用于表示一个统一资源定位符,它提供了解析和操作 URL 的方法。通过 URL 类,可以获取协议、主机名、端口、路径和查询参数等信息。

HttpURLConnection 类的作用

HttpURLConnection 是 URLConnection 的子类,专门用于处理 HTTP 请求和响应。它支持多种 HTTP 方法(如 GET、POST、PUT、DELETE 等),并允许设置请求头、读取响应内容和处理状态码。

示例:发送 HTTP GET 请求并处理响应

以下代码展示了如何使用 URL 和 HttpURLConnection 发送 HTTP GET 请求,并读取响应内容:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpGetExample {
    public static void main(String[] args) {
        try {
            // 创建 URL 对象
            URL url = new URL("https://jsonplaceholder.typicode.com/posts/1");

            // 打开 HTTP 连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为 GET
            connection.setRequestMethod("GET");

            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            // 读取响应内容
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 打印响应内容
                System.out.println("Response: " + response.toString());
            } else {
                System.out.println("GET request failed");
            }

            // 关闭连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

示例:发送 HTTP POST 请求并处理响应

以下代码展示了如何使用 URL 和 HttpURLConnection 发送 HTTP POST 请求,并提交 JSON 数据:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpPostExample {
    public static void main(String[] args) {
        try {
            // 创建 URL 对象
            URL url = new URL("https://jsonplaceholder.typicode.com/posts");

            // 打开 HTTP 连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为 POST
            connection.setRequestMethod("POST");

            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");

            // 允许输出流
            connection.setDoOutput(true);

            // 准备 JSON 数据
            String jsonInputString = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";

            // 写入请求数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            // 读取响应内容
            if (responseCode == HttpURLConnection.HTTP_CREATED) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 打印响应内容
                System.out.println("Response: " + response.toString());
            } else {
                System.out.println("POST request failed");
            }

            // 关闭连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

总结

  1. URL 类主要用于解析和操作 URL。
  2. HttpURLConnection 类提供了发送 HTTP 请求和处理响应的功能。
  3. 通过设置请求方法、请求头和输出流,可以实现 GET 和 POST 请求。
  4. 响应内容可以通过输入流读取,并根据需要进行处理。

以上示例展示了 URL 和 HttpURLConnection 的基本用法,适用于常见的 HTTP 请求场景。