鸿蒙NEXT中发起HTTP网络请求:基础实现
在鸿蒙NEXT中,网络请求通常通过@ohos.net.http模块实现。该模块提供了完整的HTTP客户端功能,支持GET、POST等常见请求方法。
import http from '@ohos.net.http';
// 创建HTTP请求对象
let httpRequest = http.createHttp();
// 配置请求参数
let url = 'https://api.example.com/data';
let requestOptions = {
method: 'GET', // 请求方法
header: {
'Content-Type': 'application/json'
}
};
// 发起请求
httpRequest.request(url, requestOptions, (err, data) => {
if (err) {
console.error('请求失败:', err);
return;
}
console.log('响应状态码:', data.responseCode);
console.log('响应数据:', data.result);
});
处理POST请求与JSON数据
POST请求需要额外设置请求体数据,特别是处理JSON格式数据时需注意头部设置。
let postOptions = {
method: 'POST',
header: {
'Content-Type': 'application/json'
},
extraData: JSON.stringify({
username: 'testUser',
password: '123456'
})
};
httpRequest.request('https://api.example.com/login', postOptions, (err, data) => {
if (err) {
console.error('登录失败:', err);
return;
}
let response = JSON.parse(data.result);
console.log('登录成功:', response.token);
});
高级请求配置与超时处理
网络请求需要配置超时时间并处理可能出现的异常情况,确保应用稳定性。
let advancedOptions = {
method: 'GET',
header: {
'Cache-Control': 'no-cache'
},
connectTimeout: 60000, // 连接超时60秒
readTimeout: 60000 // 读取超时60秒
};
httpRequest.request(url, advancedOptions, (err, data) => {
if (err) {
if (err.code === http.ResponseCode.TIMEOUT_ERROR) {
console.error('请求超时');
} else {
console.error('请求错误:',
9854

被折叠的 条评论
为什么被折叠?



