构造 HTTP 请求,取决于你是手动构造、用代码、还是用工具。下面从常见场景给你一个清晰、实用的说明。
一个 HTTP 请求通常包含:
请求行(Method + URL + 协议版本)
请求头(Headers)
空行
请求体(Body,可选)
GET /api/users?id=1 HTTP/1.1
Host: example.com
User-Agent: MyClient/1.0
Accept: application/json
POST /api/users HTTP/1.1
Host: example.com
Content-Type: application/json
Content-Length: 27
{
"name": "Tom",
"age": 18
}
✅ 适合:查看请求,不适合主动构造复杂请求
最常用方式
步骤:
GET / POST / PUT / DELETEhttps://example.com/api/usersAuthorization)✅ 适合:接口调试、快速构造
import requests
response = requests.get(
"https://example.com/api/users",
params={"id": 1},
headers={"Authorization": "Bearer token123"}
)
print(response.status_code)
print(response.json())
import requests
response = requests.post(
"https://example.com/api/users",
json={"name": "Tom", "age": 18},
headers={"Authorization": "Bearer token123"}
)
fetch("https://example.com/api/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer token123"
},
body: JSON.stringify({
name: "Tom",
age: 18
})
})
.then(res => res.json())
.then(data => console.log(data));
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/api/users"))
.header("Authorization", "Bearer token123")
.POST(HttpRequest.BodyPublishers.ofString(
"{\"name\":\"Tom\"}"
))
.build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenAccept(System.out::println);
| 方法 | 含义 |
|---|---|
| GET | 获取资源 |
| POST | 创建资源 |
| PUT | 更新资源 |
| DELETE | 删除资源 |
| PATCH | 局部更新 |
| Header | 作用 |
|---|---|
Content-Type |
请求体格式 |
Authorization |
认证 |
User-Agent |
客户端标识 |
Accept |
期望返回格式 |
| 类型 | 使用场景 |
|---|---|
application/json |
JSON 接口 |
application/x-www-form-urlencoded |
表单 |
multipart/form-data |
文件上传 |
URL + 方法 + 参数 + 请求头 + 请求体
你可以告诉我:
我可以给你完全贴合你场景的示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。