Java HTTP客户端:正确发送请求

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

HTTP 客户端在 Java 中:正确发送请求



在现代开发中,几乎任何应用程序都会通过 HTTP 与外部服务交互。无论是 REST API、从服务器加载数据还是提交表单,掌握 HTTP 请求的处理能力是 Java 开发者的必备技能。在本文中,我们将探讨如何使用标准工具和流行的第三方库在 Java 中创建 HTTP 客户端。您将学习如何正确执行 GET 和 POST 请求、处理错误以及解析响应。



1. 经典方法:HttpURLConnection



长期以来,Java 中处理 HTTP 的标准方式是使用 HttpURLConnection 类。它包含在 java.net 包中,无需安装额外依赖。下面是一个执行 GET 请求的示例:



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

public class SimpleHttpClient { public static void main(String[] args) throws Exception { URL url = new URL("https://api.example.com/data"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json");

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(); }}


对于传递 JSON 数据的 POST 请求,代码会稍微复杂一些:



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

public class PostExample { public static void main(String[] args) throws Exception { URL url = new URL("https://api.example.com/users"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true);

String jsonInput = "{\\"name\\":\\"John\\",\\"email\\":\\"john@example.com\\"}";

try (OutputStream os = connection.getOutputStream()) { byte[] input = jsonInput.getBytes("utf-8"); os.write(input, 0, input.length); }

int responseCode = connection.getResponseCode(); System.out.println("POST Response Code: " + responseCode);

if (responseCode == HttpURLConnection.HTTP_CREATED) { // 读取响应,与 GET 类似 } connection.disconnect(); }}


HttpURLConnection 的优点:

  • 无需额外库
  • 完全控制请求
  • 支持所有 HTTP 方法


缺点:

  • API 冗长且不便
  • 错误处理复杂
  • 没有内置对现代协议(HTTP/2)的支持


2. 现代标准:HttpClient (Java 11+)



从 Java 11 开始,标准库中新增了 java.net.http.HttpClient。它提供了现代、异步且更加便捷的 API。以下是使用它执行 GET 请求的方式:



import java.net.URI;import java.net.http.HttpClient;import java.net.ht                

博客

书籍推荐