全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-11 6 分钟 ✍️ juanwangdev

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/jsonJSON数据
application/xmlXML数据
text/htmlHTML页面
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

要点总结

  1. HTTP请求包含请求行、请求头、请求体
  2. 常用方法:GET获取、POST提交、PUT更新、DELETE删除
  3. 状态码2xx成功、4xx客户端错误、5xx服务端错误
  4. Java 11+ 推荐使用 HttpClient,支持同步和异步
  5. 重要请求头:Content-Type、Accept、Authorization

📝 发现内容有误?点击此处直接编辑

← 上一篇 Java TCP/IP协议
下一篇 → Java RPC原理
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库