鸿蒙Next中如何实现http拦截器功能
在鸿蒙Next开发中,我想实现HTTP请求的拦截功能,例如在发送请求前统一添加Header,或者对响应结果进行预处理。请问应该如何实现这样的拦截器?有没有具体的代码示例或最佳实践可以参考?目前官方文档中似乎没有明确说明这部分内容。
2 回复
在鸿蒙Next中实现HTTP拦截器,可以通过以下步骤:
- 创建拦截器接口:定义拦截器接口,包含请求前、响应后等方法。
- 实现拦截器:编写具体拦截逻辑,例如添加公共请求头、日志记录、错误处理等。
- 注册拦截器:在初始化HTTP客户端时,将拦截器添加到拦截器链中。
- 链式调用:在发送请求和接收响应时,按顺序执行拦截器。
示例代码:
// 定义拦截器
class MyInterceptor implements Interceptor {
onRequest(request: Request): Request {
// 修改请求,如添加Header
request.headers.set('Token', 'xxx');
return request;
}
onResponse(response: Response): Response {
// 处理响应,如统一错误码
if (response.code !== 200) {
// 错误处理
}
return response;
}
}
// 注册拦截器
httpClient.addInterceptor(new MyInterceptor());
通过拦截器可统一处理网络请求,提升代码复用性和可维护性。
更多关于鸿蒙Next中如何实现http拦截器功能的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在鸿蒙Next中,可以通过@ohos.net.http模块的拦截器机制实现HTTP请求拦截功能。以下是具体实现方法:
核心实现代码
import http from '@ohos.net.http';
// 创建HTTP请求实例
let httpRequest = http.createHttp();
// 请求拦截器
httpRequest.on('requestIntercept', (request) => {
console.log('请求拦截器触发');
// 添加公共请求头
request.header = {
...request.header,
'Content-Type': 'application/json',
'Authorization': 'Bearer your-token-here'
};
// 修改请求参数
if (request.extraData) {
request.extraData.timestamp = new Date().getTime();
}
return request;
});
// 响应拦截器
httpRequest.on('responseIntercept', (response) => {
console.log('响应拦截器触发');
// 统一处理响应数据
if (response.responseCode === 200) {
try {
const data = JSON.parse(response.result.toString());
// 业务逻辑处理
if (data.code !== 0) {
console.error('业务错误:', data.message);
}
return data;
} catch (error) {
console.error('响应数据解析失败');
return null;
}
} else {
console.error('网络请求失败:', response.responseCode);
return null;
}
});
// 发送请求示例
async function fetchData() {
try {
const response = await httpRequest.request(
"https://api.example.com/data",
{
method: http.RequestMethod.GET,
}
);
console.log('请求结果:', response);
} catch (error) {
console.error('请求异常:', error);
}
}
关键特性
-
请求拦截器 (
requestIntercept):- 在请求发送前执行
- 可修改请求头、参数
- 添加认证信息
-
响应拦截器 (
responseIntercept):- 在收到响应后执行
- 统一处理响应数据
- 错误状态码处理
-
事件监听机制:
- 使用
on()方法注册拦截器 - 支持多个拦截器链式调用
- 使用
使用场景
- 统一添加认证令牌
- 请求参数加密/解密
- 响应数据格式统一处理
- 错误状态码全局处理
- 请求日志记录
这种拦截器机制可以有效减少重复代码,统一处理网络请求的公共逻辑。

