杰瑞科技汇

Java HTTP GET请求怎么写?

在 Java 中,你可以使用多种方式发送 HTTP GET 请求,以下是几种常见的方法,从传统的 HttpURLConnection 到现代的 HttpClient(Java 11+)。

Java HTTP GET请求怎么写?-图1
(图片来源网络,侵删)

使用 HttpURLConnection (JDK 内置,无需额外依赖)

这是最传统的方式,从 Java 1.1 开始就存在,无需添加任何第三方库。

简单 GET 请求(无参数)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class SimpleGetRequest {
    public static void main(String[] args) {
        String urlString = "https://jsonplaceholder.typicode.com/posts/1"; // 示例 API
        try {
            // 1. 创建 URL 对象
            URL url = new URL(urlString);
            // 2. 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 3. 设置请求方法为 GET
            connection.setRequestMethod("GET");
            // 4. 设置请求头 (可选)
            connection.setRequestProperty("User-Agent", "MyJavaApp/1.0");
            // 5. 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            // 6. 如果请求成功 (200 OK),读取响应数据
            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();
                // 7. 打印响应内容
                System.out.println("Response: " + response.toString());
            } else {
                System.out.println("GET request failed");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

带 Query 参数的 GET 请求

GET 请求的参数通常通过 URL 的查询字符串(Query String)传递,你需要手动构建完整的 URL。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class GetWithParams {
    public static void main(String[] args) {
        // API 端点
        String baseUrl = "https://jsonplaceholder.typicode.com/posts";
        // 参数
        String userId = "1";
        String title = "sunt aut facere repellat provident occaecati excepturi optio reprehenderit";
        try {
            // 对参数进行 URL 编码,防止特殊字符引起问题
            String encodedUserId = URLEncoder.encode(userId, StandardCharsets.UTF_8.toString());
            String encodedTitle = URLEncoder.encode(title, StandardCharsets.UTF_8.toString());
            // 构建带参数的完整 URL
            String urlString = String.format("%s?userId=%s&id=%s", baseUrl, encodedUserId, encodedTitle);
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            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());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

使用 HttpClient (Java 11+ 推荐方式)

从 Java 11 开始,java.net.http.HttpClient 成为官方推荐的 HTTP 客户端 API,它更现代化、功能更强大(支持异步请求、WebSocket 等),API 设计更友好。

同步 GET 请求

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 HttpClientSyncGet {
    public static void main(String[] args) {
        String urlString = "https://jsonplaceholder.typicode.com/posts/1";
        // 1. 创建 HttpClient
        HttpClient client = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_2) // 指定 HTTP 版本
                .connectTimeout(Duration.ofSeconds(10)) // 设置连接超时
                .build();
        // 2. 创建 HttpRequest
        HttpRequest request = HttpRequest.newBuilder()
                .GET() // GET 请求是默认的,可以省略
                .uri(URI.create(urlString))
                .header("User-Agent", "MyJavaApp/1.0") // 设置请求头
                .build();
        try {
            // 3. 发送请求并获取响应 (同步方式)
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            // 4. 处理响应
            System.out.println("Status Code: " + response.statusCode());
            System.out.println("Response Headers: " + response.headers());
            System.out.println("Response Body: " + response.body());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

带 Query 参数的 GET 请求

HttpClient 提供了更优雅的方式来处理查询参数。

Java HTTP GET请求怎么写?-图2
(图片来源网络,侵删)
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.net.http.HttpResponse.BodyHandlers;
import java.util.Map;
public class HttpClientGetWithParams {
    public static void main(String[] args) {
        String baseUrl = "https://jsonplaceholder.typicode.com/posts";
        // 使用 Map 存储参数
        Map<String, String> params = Map.of(
            "userId", "1",
            "id", "1"
        );
        try {
            // 1. 构建带查询参数的 URI
            URI uri = URI.create(baseUrl + "?" + formatQueryParams(params));
            // 2. 创建 HttpClient 和 HttpRequest
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(uri)
                    .GET()
                    .build();
            // 3. 发送请求
            HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
            // 4. 处理响应
            System.out.println("Status Code: " + response.statusCode());
            System.out.println("Response Body: " + response.body());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 辅助方法:将 Map 格式化为查询字符串
    private static String formatQueryParams(Map<String, String> params) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(entry.getKey())
              .append("=")
              .append(entry.getValue());
        }
        return sb.toString();
    }
}

使用第三方库 (如 OkHttp, Apache HttpClient)

在实际项目中,为了更简洁的 API 和更强的功能,开发者常常会选择成熟的第三方库。

使用 OkHttp (非常流行)

添加 Maven 依赖:

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.12.0</version> <!-- 请使用最新版本 -->
</dependency>

示例代码:

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpGetExample {
    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();
        String url = "https://jsonplaceholder.typicode.com/posts/1";
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            // 获取响应体
            String responseBody = response.body().string();
            System.out.println("Response Body: " + responseBody);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

总结与选择

方法 优点 缺点 适用场景
HttpURLConnection - JDK 内置,无需依赖
- 简单 GET 请求足够
- API 陈旧,使用繁琐
- 处理复杂请求(如流、异步)很困难
学习、简单脚本、对依赖有严格限制的环境
HttpClient (Java 11+) - 官方推荐,现代 API
- 功能强大(同步/异步/WebSocket)
- API 设计清晰
- 需要 Java 11 或更高版本 新项目、Java 11+ 环境,是未来的标准
OkHttp / Apache HttpClient - API 简洁易用
- 功能强大且稳定
- 社区活跃,文档完善
- 需要添加第三方依赖 绝大多数生产环境项目,特别是需要高级功能时

建议:

Java HTTP GET请求怎么写?-图3
(图片来源网络,侵删)
  • 如果你使用的是 Java 11 或更高版本,优先选择 java.net.http.HttpClient
  • 如果你使用的是 Java 8 或更早版本,或者项目已经引入了 OkHttp/Apache HttpClient,那么使用它们是更好的选择。
  • 对于快速原型或简单的工具脚本HttpURLConnection 也能完成任务,但代码量会多一些。
分享:
扫描分享到社交APP
上一篇
下一篇