第8章:数据持久化与网络请求
网络请求
在现代移动应用开发中,网络请求是获取远程数据、与服务器交互的核心功能。ArkTS提供了强大的网络请求能力,支持HTTP/HTTPS协议,能够满足各种网络通信需求。
8.4.1 网络请求基础
ArkTS中的网络请求主要基于@ohos.net.http模块实现,该模块提供了完整的HTTP客户端功能:
import http from '@ohos.net.http';
创建HTTP请求对象
let httpRequest = http.createHttp();
基本请求方法
ArkTS支持常见的HTTP请求方法:
- GET:获取资源
- POST:创建资源
- PUT:更新资源
- DELETE:删除资源
8.4.2 发起GET请求
GET请求是最常用的请求方式,用于从服务器获取数据:
// 创建请求对象
let httpRequest = http.createHttp();
// 发起GET请求
httpRequest.request(
"https://api.example.com/data",
{
method: http.RequestMethod.GET,
header: {
'Content-Type': 'application/json'
}
},
(err, data) => {
if (!err) {
// 请求成功
console.log('Result:' + data.result);
console.log('Code:' + data.responseCode);
console.log('Headers:' + JSON.stringify(data.header));
console.log('Cookies:' + data.cookies);
} else {
// 请求失败
console.log('error:' + JSON.stringify(err));
}
// 销毁请求对象
httpRequest.destroy();
}
);
8.4.3 发起POST请求
POST请求通常用于向服务器提交数据:
let httpRequest = http.createHttp();
httpRequest.request(
"https://api.example.com/create",
{
method: http.RequestMethod.POST,
header: {
'Content-Type': 'application/json'
},
extraData: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
})
},
(err, data) => {
if (!err) {
console.log('Response:' + data.result);
} else {
console.log('Error:' + JSON.stringify(err));
}
httpRequest.destroy();
}
);
8.4.4 处理响应数据
网络请求返回的数据通常需要进行解析和处理:
// 解析JSON响应
if (data.result) {
try {
let responseData = JSON.parse(data.result);
console.log('Parsed data:', responseData);
} catch (e) {
console.log('JSON parse error:', e);
}
}
8.4.5 错误处理
完善的错误处理是网络请求的重要组成部分:
if (err) {
// 网络错误
if (err.code === 1) {
console.log('Network unavailable');
}
// 超时错误
else if (err.code === 2) {
console.log('Request timeout');
}
// 其他错误
else {
console.log('Other error:', JSON.stringify(err));
}
return;
}
// 检查HTTP状态码
if (data.responseCode !== 200) {
console.log('HTTP error:', data.responseCode);
return;
}
8.4.6 高级功能
设置请求超时
{
method: http.RequestMethod.GET,
connectTimeout: 60000, // 连接超时时间(毫秒)
readTimeout: 60000 // 读取超时时间(毫秒)
}
文件上传
import fileio from '@ohos.fileio';
let filePath = '...'; // 文件路径
let fileStat = fileio.statSync(filePath);
let file = fileio.openSync(filePath, 0o2);
httpRequest.upload(
"https://api.example.com/upload",
{
files: [
{
filename: 'image.jpg',
name: 'file',
uri: filePath,
type: 'image/jpeg'
}
],
data: [
{
name: 'description',
value: 'This is an image file'
}
]
},
(err, data) => {
fileio.closeSync(file);
// 处理响应
}
);
文件下载
httpRequest.download(
"https://example.com/largefile.zip",
{
filePath: 'path/to/save/file.zip'
},
(err, data) => {
if (!err) {
console.log('Download complete:', data.filePath);
} else {
console.log('Download error:', err);
}
}
);
8.4.7 安全注意事项
- HTTPS优先:始终使用HTTPS协议而非HTTP
- 证书验证:确保服务器证书有效
- 敏感数据:不要在URL中传递敏感信息
- 权限配置:在
config.json中添加网络权限
{
"module": {
"reqPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
}
}
8.4.8 最佳实践
- 封装网络请求:创建统一的网络请求工具类
- 错误重试机制:对可重试错误实现自动重试
- 请求取消:在组件销毁时取消未完成的请求
- 缓存策略:合理使用缓存减少网络请求
- 性能监控:记录和分析网络请求性能
// 网络请求工具类示例
class HttpUtil {
private static instance: HttpUtil;
private httpRequest: http.HttpRequest;
private constructor() {
this.httpRequest = http.createHttp();
}
public static getInstance(): HttpUtil {
if (!HttpUtil.instance) {
HttpUtil.instance = new HttpUtil();
}
return HttpUtil.instance;
}
public get(url: string, params?: object): Promise<any> {
return new Promise((resolve, reject) => {
// 实现GET请求逻辑
});
}
public post(url: string, data: object): Promise<any> {
return new Promise((resolve, reject) => {
// 实现POST请求逻辑
});
}
// 其他方法...
}
通过本章学习,您应该已经掌握了ArkTS中进行网络请求的基本方法和高级技巧。在实际开发中,建议根据项目需求封装适合的网络请求工具,以提高代码复用性和可维护性。
