|
|
@@ -4,18 +4,71 @@ import java.io.IOException;
|
|
|
import java.net.URI;
|
|
|
import java.net.http.HttpClient;
|
|
|
import java.net.http.HttpRequest;
|
|
|
+import java.net.http.HttpResponse;
|
|
|
|
|
|
+/**
|
|
|
+ * GET 请求示例:演示发送 GET 请求的两种常见场景
|
|
|
+ *
|
|
|
+ * <ul>
|
|
|
+ * <li>GET 请求列表:查询所有用户 GET /api/users</li>
|
|
|
+ * <li>GET 请求单个资源:根据 id 查询用户 GET /api/users/{id}</li>
|
|
|
+ * </ul>
|
|
|
+ */
|
|
|
public class GetExample {
|
|
|
- public void process() throws IOException, InterruptedException {
|
|
|
+
|
|
|
+ /** 服务基地址常量 */
|
|
|
+ private static final String BASE_URL = "http://localhost:8080";
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 发送一个不带参数的 GET 请求,查询所有用户。
|
|
|
+ *
|
|
|
+ * @return 响应对象,可通过 statusCode()/body() 获取状态码和响应体
|
|
|
+ */
|
|
|
+ public HttpResponse<String> getUsers() throws IOException, InterruptedException {
|
|
|
+ // 创建 HttpClient,newHttpClient() 使用默认配置
|
|
|
HttpClient httpClient = HttpClient.newHttpClient();
|
|
|
- HttpRequest httpRequest = HttpRequest.newBuilder()
|
|
|
- //设置请求的URL
|
|
|
- .uri(URI.create("http://www.baidu.com"))
|
|
|
- //设置请求方法为GET
|
|
|
+
|
|
|
+ // 构造 GET 请求:.GET() 显式声明请求方法(省略时默认为 GET)
|
|
|
+ HttpRequest request = HttpRequest.newBuilder()
|
|
|
+ .uri(URI.create(BASE_URL + "/api/users"))
|
|
|
.GET()
|
|
|
- //设置请求头
|
|
|
- .header("Content-Type", "application/json")
|
|
|
.build();
|
|
|
|
|
|
+ // 发送请求并返回响应
|
|
|
+ return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 发送一个带路径参数的 GET 请求,根据用户 id 查询单个用户。
|
|
|
+ *
|
|
|
+ * @param id 用户 id,会拼接在 URL 路径中
|
|
|
+ * @return 响应对象;若用户存在则状态码为 200,否则为 404
|
|
|
+ */
|
|
|
+ public HttpResponse<String> getUserById(long id) throws IOException, InterruptedException {
|
|
|
+ HttpClient httpClient = HttpClient.newHttpClient();
|
|
|
+
|
|
|
+ // 通过字符串拼接把 id 拼进 URL 路径,形成 /api/users/1 这样的地址
|
|
|
+ HttpRequest request = HttpRequest.newBuilder()
|
|
|
+ .uri(URI.create(BASE_URL + "/api/users/" + id))
|
|
|
+ .GET()
|
|
|
+ .build();
|
|
|
+
|
|
|
+ return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 演示如何按条件查询。本服务不支持查询参数,这里展示标准写法:
|
|
|
+ * 通过 {@link URI#create(String)} 拼上 ?key=value 的查询字符串。
|
|
|
+ *
|
|
|
+ * <p>此方法不实际调用(服务无此接口),仅用于讲解构造带查询字符串的 GET 请求。</p>
|
|
|
+ */
|
|
|
+ public HttpRequest buildRequestWithQuery(String account) {
|
|
|
+ // 查询字符串格式:?参数名=参数值,多个参数用 & 连接
|
|
|
+ URI uri = URI.create(BASE_URL + "/api/users?account=" + account);
|
|
|
+
|
|
|
+ return HttpRequest.newBuilder()
|
|
|
+ .uri(uri)
|
|
|
+ .GET()
|
|
|
+ .build();
|
|
|
}
|
|
|
-}
|
|
|
+}
|