Network - HTTP 客户端
network 命名空间提供了一个完整的 HTTP 客户端,支持常见的 HTTP 方法(GET、POST、PUT、DELETE、HEAD 等),并提供灵活的头部管理和响应处理功能。
版本说明
network 命名空间在 SDK v0.3.2 中引入,取代了旧版的 httpClient 命名空间。旧版 httpClient 仍然可用但建议迁移至 network。
核心接口
HeaderCollection
HTTP 头部集合管理接口:
interface HeaderCollection {
[key: string]: string; // 索引器访问
Set(key: string, value: string): void;
Get(key: string): string;
Contains(key: string): boolean;
Remove(key: string): boolean;
Clear(): void;
GetKeys(): string[];
GetValues(): string[];
}
RequestMessage
HTTP 请求消息结构:
interface RequestMessage {
url: string; // 请求URL
method: string; // HTTP方法
headers: HeaderCollection; // 请求头部
body?: string; // 请求体(可选)
}
ResponseMessage
HTTP 响应消息结构:
interface ResponseMessage {
status: number; // 状态码
headers: HeaderCollection; // 响应头部
body: string; // 响应体
data?: any; // JSON反序列化对象(可选)
}
方法详解
request()
功能描述:发送自定义 HTTP 请求,支持自定义方法、头部和请求体。
语法:
network.request(message: RequestMessage): Promise<ResponseMessage>
参数:
message:完整的请求参数对象url:请求 URLmethod:HTTP 方法headers:请求头集合body:请求体(可选)
使用示例:
const response = await network.request({
url: "https://api.example.com/data",
method: "PATCH",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer token123"
},
body: JSON.stringify({ status: "active" })
});
logger.info(`状态码: ${response.status}`);
logger.info(`响应: ${response.body}`);
get()
功能描述:发送 GET 请求。
语法:
network.get(url: string): Promise<ResponseMessage>
使用示例:
const response = await network.get("https://api.example.com/users");
if (response.status === 200) {
const users = response.data; // 自动JSON反序列化
logger.info(`获取到 ${users.length} 个用户`);
}
post()
功能描述:发送 POST 请求。
语法:
network.post(url: string, body: any): Promise<ResponseMessage>
使用示例:
const response = await network.post(
"https://api.example.com/users",
JSON.stringify({ name: "张三", email: "zhangsan@example.com" })
);
if (response.status === 201) {
logger.info("用户创建成功");
}
put()
功能描述:发送 PUT 请求。
语法:
network.put(url: string, body: any): Promise<ResponseMessage>
del()
功能描述:发送 DELETE 请求。
语法:
network.del(url: string): Promise<ResponseMessage>
使用示例:
const response = await network.del("https://api.example.com/users/123");
if (response.status === 204) {
logger.info("用户已删除");
}
head()
功能描述:发送 HEAD 请求,仅获取响应头。
语法:
network.head(url: string): Promise<ResponseMessage>
HeaderCollection 方法
索引器访问
直接通过 [] 操作符读写头部:
// 设置
headers["Content-Type"] = "application/json";
// 读取
const contentType = headers["Content-Type"];
Set() / Get()
headers.Set("Authorization", "Bearer token123");
const auth = headers.Get("Authorization");
Contains()
检查是否包含指定头部:
if (headers.Contains("X-Custom-Header")) {
logger.info("包含自定义头部");
}
Remove()
移除指定头部:
headers.Remove("X-Unused-Header");
Clear()
清空所有头部:
headers.Clear();