Request 是一个基于 Rust reqwest 的高效率 ArkTs HTTP 客户端
- 支持HTTP/2
- 简洁的链式调用API
- 支持多种responseBody转换策略
ohpm install @axzo/ok-request
开启网络请求权限 module.json5
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
],创建配置config
const config: OkConfig = {
requestInterceptors: [],
responseInterceptors: [],
timeout: 30,
maxConnections: 5,
baseUrl: undefined,
protocols: undefined,
tlsConfig: undefined
}
config.requestInterceptors.push({
intercept: (request: Request) => {
return request.newBuilder()
.head('1', '2')
.build()
}
})
config.responseInterceptors.push({
intercept: (response: Response | undefined) => {
return response
}
})
config.setBaseUrl('baseUrl')创建client
let client = new OkHttpClient(config)let res: ResponseBody = await this.client.get('https://baidu.com').send()json body
let res: ResponseBody = await this.client.post('xx/xx/xx').json({
s: '1',
a: 2
}).send()let res: ResponseBody = await this.client.post('xx/xx/xx').json({
s: '1',
a: 2
}).head('name', 'value').head('xxx', 'xxxx').send()await this.client.post('xxx.xxx.xx').dns([{address:'192.168.1.1', family: 1}]).json({
s: '1',
a: 2
}).send()TEXT 解析
res?.text()JSON 解析
res?.json<T>()ArrayBuffer
res?.bytes()取消当前client所有请求
this.client.cancelAll()根据requestId取消请求
let request = this.client.get('https://baidu.com').build()
await this.client.execute(request)
this.client.cancel(request)let result = await this.client.post('xxx.xxx.xxx').file(new FileBody(path, contentType)).send()let multipart = new MultiPartBodyBuilder()
.addFormDataPart('file', 'filename.txt', new FileBody(path, "text/plain"))
.addTextFormDataPart('key', 'dsa')
.build()
let result = await this.client.post('xxx.xxx.xxx').multipart(multipart).send()// SSE 简单用法
await this.client.get('https://api.example.com/events')
.sse(
(msg: string) => {
console.info('收到 SSE 消息:', msg);
},
(err: any) => {
console.error('SSE 错误:', err);
}
);
// 带请求头和查询参数的 SSE
await this.client.get('https://api.example.com/events')
.head('Authorization', 'Bearer token123')
.query({ type: 'updates' })
.sse(
(msg: string) => {
// 处理每条事件消息
console.info('收到消息:', msg);
},
(err: any) => {
// 处理错误(可选)
console.error('发生错误:', err);
}
); await this.client.get('https://api.example.com/events')
.sse(
(msg: string) => {
console.info('收到 SSE 消息:', msg);
},
(err: Error) => {
console.error('SSE 错误:', err);
}
);try {
await this.client.get('https://baidu.com').send()
} catch(e: HttpError) {
}