Java HTTP协议
HTTP(HyperText Transfer Protocol)是Web应用的基础协议,无状态、基于请求-响应模式。
HTTP请求结构
Java
请求行:方法 URL 协议版本
请求头:HeaderName: HeaderValue
请求体:数据内容
请求示例
Java
POST /api/user HTTP/1.1
Host: www.example.com
Content-Type: application/json
Content-Length: 25
User-Agent: Java/11
{"name":"张三","age":25}
HTTP响应结构
text
状态行:协议版本 状态码 状态描述
响应头:HeaderName: HeaderValue
响应体:数据内容
响应示例
text
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 42
Date: Sat, 11 May 2026 08:00:00 GMT
{"id":1,"name":"张三","age":25}
HTTP方法
| 方法 | 作用 | 是否有请求体 |
|---|---|---|
| GET | 获取资源 | 无 |
| POST | 提交数据 | 有 |
| PUT | 更新资源 | 有 |
| DELETE | 删除资源 | 可选 |
| HEAD | 获取响应头 | 无 |
| OPTIONS | 获取支持方法 | 无 |
HTTP状态码
| 状态码 | 类别 | 示例 |
|---|---|---|
| 1xx | 信息响应 | 100 Continue |
| 2xx | 成功 | 200 OK, 201 Created |
| 3xx | 重定向 | 301 Moved, 304 Not Modified |
| 4xx | 客户端错误 | 400 Bad Request, 404 Not Found |
| 5xx | 服务端错误 | 500 Internal Error, 503 Unavailable |
常用请求头
| 请求头 | 作用 |
|---|---|
| Host | 目标主机 |
| Content-Type | 请求体类型 |
| Content-Length | 请求体长度 |
| Accept | 可接受的响应类型 |
| User-Agent | 客户端标识 |
| Authorization | 认证信息 |
| Cookie | 会话标识 |
常用响应头
| 响应头 | 作用 |
|---|---|
| Content-Type | 响应体类型 |
| Content-Length | 响应体长度 |
| Set-Cookie | 设置Cookie |
| Location | 重定向地址 |
| Cache-Control | 缓存控制 |
| Expires | 过期时间 |
Java HTTP客户端
HttpURLConnection(传统方式)
text
public class HttpUtil {
public static String get(String url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
int code = conn.getResponseCode();
if (code == 200) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
return result.toString();
}
conn.disconnect();
return null;
}
public static String post(String url, String body) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
OutputStream out = conn.getOutputStream();
out.write(body.getBytes());
out.flush();
int code = conn.getResponseCode();
if (code == 200) {
InputStream in = conn.getInputStream();
// 读取响应...
}
conn.disconnect();
return null;
}
}
HttpClient(Java 11+)
text
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class ModernHttpClient {
private static final HttpClient client = HttpClient.newHttpClient();
// GET请求
public static String get(String url) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
return response.body();
}
// POST请求
public static String post(String url, String body) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
return response.body();
}
// 异步请求
public static CompletableFuture<String> getAsync(String url) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.build();
return client.sendAsync(request,
HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body);
}
}
Content-Type常见值
| 类型 | 说明 |
|---|---|
| application/json | JSON数据 |
| application/xml | XML数据 |
| text/html | HTML页面 |
| text/plain | 纯文本 |
| multipart/form-data | 表单上传文件 |
| application/x-www-form-urlencoded | 表单数据 |
注意事项
HTTP/1.1 默认持久连接,Connection: keep-alive
POST请求需设置 Content-Type 和 Content-Length
状态码4xx表示客户端问题,5xx表示服务端问题
HttpURLConnection 只支持HTTP协议,HTTPS需设置SSL
要点总结
- HTTP请求包含请求行、请求头、请求体
- 常用方法:GET获取、POST提交、PUT更新、DELETE删除
- 状态码2xx成功、4xx客户端错误、5xx服务端错误
- Java 11+ 推荐使用 HttpClient,支持同步和异步
- 重要请求头:Content-Type、Accept、Authorization
📝 发现内容有误?点击此处直接编辑