Java 发送 PUT 请求详解

在 Java 开发中,HTTP PUT 请求常用于更新服务器上的资源,与 GET 请求不同,PUT 请求携带的数据通常用于更新服务器上的资源,而不是获取资源,本文将详细介绍如何在 Java 中发送 PUT 请求,包括使用 Java 标准库和第三方库两种方法。
使用 Java 标准库发送 PUT 请求
Java 标准库提供了 HttpURLConnection 类,可以用来发送 HTTP 请求,以下是如何使用 HttpURLConnection 发送 PUT 请求的步骤:

- 创建
HttpURLConnection对象 - 设置请求方法为 “PUT”
- 设置请求头(如 Content-Type)
- 发送请求体(如果需要)
- 读取响应
下面是一个简单的示例代码:
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class PutRequestExample {
public static void main(String[] args) {
try {
// 创建 URL 对象
URL url = new URL("http://example.com/api/resource");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为 PUT
connection.setRequestMethod("PUT");
// 设置请求头
connection.setRequestProperty("Content-Type", "application/json");
// 设置允许输出
connection.setDoOutput(true);
// 创建请求体
String jsonInputString = "{\"name\":\"John\", \"age\":30}";
// 发送请求体
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);
// 读取响应
// ...(此处省略响应读取代码)
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用第三方库发送 PUT 请求
除了 Java 标准库,还有很多第三方库可以帮助我们发送 HTTP 请求,如 Apache HttpClient、OkHttp 等,以下以 Apache HttpClient 为例,展示如何发送 PUT 请求:

- 添加依赖
- 创建
HttpClient对象 - 创建
HttpPut对象 - 设置请求头
- 发送请求体(如果需要)
- 读取响应
下面是一个简单的示例代码:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class PutRequestExample {
public static void main(String[] args) {
try {
// 创建 HttpClient 对象
HttpClient httpClient = HttpClients.createDefault();
// 创建 HttpPut 对象
HttpPut put = new HttpPut("http://example.com/api/resource");
// 设置请求头
put.setHeader("Content-Type", "application/json");
// 创建请求体
String jsonInputString = "{\"name\":\"John\", \"age\":30}";
// 发送请求体
put.setEntity(new org.apache.http.entity.StringEntity(jsonInputString));
// 执行请求
HttpResponse response = httpClient.execute(put);
// 获取响应码
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("Response Code : " + responseCode);
// 读取响应
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity);
System.out.println("Response : " + result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
本文介绍了两种在 Java 中发送 PUT 请求的方法:使用 Java 标准库和第三方库,通过了解这些方法,你可以根据实际需求选择合适的方式来实现 HTTP PUT 请求,在实际开发中,选择合适的库和工具可以提高开发效率和代码质量。


















