在 Java 中使用 GET 和 POST 请求

server/2025/1/13 11:14:27/

在 Java 中,我们通常使用 HttpURLConnection 或第三方库(如 Apache HttpClient 或 OkHttp)来发送 GET 和 POST 请求。本文将通过示例讲解如何实现这两种 HTTP 请求。


1. 使用 HttpURLConnection 实现 GET 和 POST 请求

HttpURLConnection 是 Java 原生类库中提供的工具,可以用来发送 HTTP 请求。

1.1 GET 请求示例
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;public class GetRequestExample {public static void main(String[] args) {try {// 创建 URL 对象URL url = new URL("https://jsonplaceholder.typicode.com/posts/1");// 打开连接HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");// 设置请求头(可选)connection.setRequestProperty("User-Agent", "Mozilla/5.0");// 检查响应码int responseCode = connection.getResponseCode();System.out.println("Response Code: " + responseCode);// 读取响应if (responseCode == HttpURLConnection.HTTP_OK) { // 200BufferedReader 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.");}} catch (Exception e) {e.printStackTrace();}}
}


1.2 POST 请求示例
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;public class PostRequestExample {public static void main(String[] args) {try {// 创建 URL 对象URL url = new URL("https://jsonplaceholder.typicode.com/posts");// 打开连接HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("POST");// 设置请求头connection.setRequestProperty("Content-Type", "application/json; utf-8");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) { // 201BufferedReader 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.");}} catch (Exception e) {e.printStackTrace();}}
}


2. 使用 Apache HttpClient 实现 GET 和 POST 请求

Apache HttpClient 是一个强大的第三方库,适合处理复杂的 HTTP 请求。

2.1 添加 Maven 依赖

在 pom.xml 文件中添加以下依赖:

<dependency><groupId>org.apache.httpcomponents.client5</groupId><artifactId>httpclient5</artifactId><version>5.2</version>
</dependency>
2.2 GET 请求示例
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 java.io.BufferedReader;
import java.io.InputStreamReader;public class ApacheHttpClientGetExample {public static void main(String[] args) {try (CloseableHttpClient httpClient = HttpClients.createDefault()) {HttpGet request = new HttpGet("https://jsonplaceholder.typicode.com/posts/1");try (CloseableHttpResponse response = httpClient.execute(request)) {System.out.println("Response Code: " + response.getCode());BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));String line;StringBuilder responseContent = new StringBuilder();while ((line = reader.readLine()) != null) {responseContent.append(line);}System.out.println("Response: " + responseContent.toString());}} catch (Exception e) {e.printStackTrace();}}
}


2.3 POST 请求示例
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.StringEntity;
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 java.io.BufferedReader;
import java.io.InputStreamReader;public class ApacheHttpClientPostExample {public static void main(String[] args) {try (CloseableHttpClient httpClient = HttpClients.createDefault()) {HttpPost post = new HttpPost("https://jsonplaceholder.typicode.com/posts");// 设置请求头post.setHeader("Content-Type", "application/json");// 设置请求体String json = "{ \"title\": \"foo\", \"body\": \"bar\", \"userId\": 1 }";post.setEntity(new StringEntity(json));try (CloseableHttpResponse response = httpClient.execute(post)) {System.out.println("Response Code: " + response.getCode());BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));String line;StringBuilder responseContent = new StringBuilder();while ((line = reader.readLine()) != null) {responseContent.append(line);}System.out.println("Response: " + responseContent.toString());}} catch (Exception e) {e.printStackTrace();}}
}


3. 使用 OkHttp 实现 GET 和 POST 请求

OkHttp 是另一个流行的 HTTP 客户端库,轻量且易用。

3.1 添加 Maven 依赖

在 pom.xml 文件中添加以下依赖:

<dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.11.0</version>
</dependency>
3.2 GET 请求示例
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;public class OkHttpGetExample {public static void main(String[] args) {OkHttpClient client = new OkHttpClient();Request request = new Request.Builder().url("https://jsonplaceholder.typicode.com/posts/1").build();try (Response response = client.newCall(request).execute()) {if (response.isSuccessful()) {System.out.println("Response: " + response.body().string());} else {System.out.println("GET request failed. Code: " + response.code());}} catch (Exception e) {e.printStackTrace();}}
}
3.3 POST 请求示例
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;public class OkHttpPostExample {public static void main(String[] args) {OkHttpClient client = new OkHttpClient();String json = "{ \"title\": \"foo\", \"body\": \"bar\", \"userId\": 1 }";RequestBody body = RequestBody.create(json, MediaType.get("application/json; charset=utf-8"));Request request = new Request.Builder().url("https://jsonplaceholder.typicode.com/posts").post(body).build();try (Response response = client.newCall(request).execute()) {if (response.isSuccessful()) {System.out.println("Response: " + response.body().string());} else {System.out.println("POST request failed. Code: " + response.code());}} catch (Exception e) {e.printStackTrace();}}
}


总结

  • HttpURLConnection 适合简单的 HTTP 请求,原生支持,无需额外依赖。
  • Apache HttpClient 功能强大,适合复杂的 HTTP 请求场

http://www.ppmy.cn/server/157996.html

相关文章

26个开源Agent开发框架调研总结(2)

根据Markets & Markets的预测&#xff0c;到2030年&#xff0c;AI Agent的市场规模将从2024年的50亿美元激增至470亿美元&#xff0c;年均复合增长率为44.8%。 Gartner预计到2028年&#xff0c;至少15%的日常工作决策将由AI Agent自主完成&#xff0c;AI Agent在企业应用中…

02-51单片机数码管与矩阵键盘

一、数码管模块 1.数码管介绍 如图所示为一个数码管的结构图&#xff1a; 说明&#xff1a; 数码管上下各有五个引脚&#xff0c;其中上下中间的两个引脚是联通的&#xff0c;一般为数码管的公共端&#xff0c;分为共阴极或共阳极&#xff1b;其它八个引脚分别对应八个二极管…

【数据结构-堆】2233. K 次增加后的最大乘积

给你一个非负整数数组 nums 和一个整数 k 。每次操作&#xff0c;你可以选择 nums 中 任一 元素并将它 增加 1 。 请你返回 至多 k 次操作后&#xff0c;能得到的 nums的 最大乘积 。由于答案可能很大&#xff0c;请你将答案对 109 7 取余后返回。 示例 1&#xff1a; 输入&…

计算机网络 (32)用户数据报协议UDP

前言 用户数据报协议&#xff08;UDP&#xff0c;User Datagram Protocol&#xff09;是计算机网络中的一种重要传输层协议&#xff0c;它提供了无连接的、不可靠的、面向报文的通信服务。 一、基本概念 UDP协议位于传输层&#xff0c;介于应用层和网络层之间。它不像TCP那样提…

Spring MVC简单数据绑定

【图书介绍】《SpringSpring MVCMyBatis从零开始学&#xff08;视频教学版&#xff09;&#xff08;第3版&#xff09;》_springspringmvcmybatis从零开始 代码、课件、教学视频与相关软件包下载-CSDN博客 《SpringSpring MVCMyBatis从零开始学(视频教学版)&#xff08;第3版&…

MySQL进阶突击系列(05)突击MVCC核心原理 | 左右护法ReadView视图和undoLog版本链强强联合

2024小结&#xff1a;在写作分享上&#xff0c;这里特别感谢CSDN社区提供平台&#xff0c;支持大家持续学习分享交流&#xff0c;共同进步。社区诚意满满的干货&#xff0c;让大家收获满满。 对我而言&#xff0c;珍惜每一篇投稿分享&#xff0c;每一篇内容字数大概6000字左右&…

pytorch小记(二):pytorch中的连接操作:torch.cat(tensors, dim=0)

pytorch小记&#xff08;二&#xff09;&#xff1a;pytorch矩阵乘法&#xff1a;torch.cat&#xff08;tensors, dim0&#xff09; 语法使用规则示例 1&#xff1a;在第 0 维&#xff08;行&#xff09;拼接示例 2&#xff1a;在第 1 维&#xff08;列&#xff09;拼接示例 3&…

【Ubuntu与Linux操作系统:十、C/C++编程】

第10章 C/C编程 10.1 Linux编程基础 Linux编程基础涵盖了C/C语言在Linux环境中的特点和使用方法。Linux以其高性能和开源特性成为系统编程的重要平台。 1. C语言与Linux的关系 Linux内核主要是用C语言编写的&#xff0c;因此学习C语言是理解Linux底层机制的必要前提。C语言的…