DevEco Studio 5.0中运行连接华为云物联网平台的代码显示网络错误的原因是什么
DevEco Studio 5.0中运行连接华为云物联网平台的代码显示网络错误的原因是什么
import http from '@ohos.net.http'
import promptAction from '@ohos.promptAction';
let httpRequest = http.createHttp();
//定义AK和SK,根据实际情况修改
let AK = ''
let SK = ''
let projectId ='68baaa7dd582f200184c27fa'
//let deviceId = 'DEVICE_TEMP_XDW_0001'68baaa7dd582f200184c27fa_0002_0_0_2025091606
let deviceId = '68baaa7dd582f200184c27fa_0002'
// ---------- 顶部:类型定义(文件顶部放一组接口) ----------
interface SensorKV {
name: string; // 属性名,例如 "co2" / "light"
value: number | string | null;
}
interface SensorProperties {
// 明确列出常用字段
temperature?: number;
humidity?: number;
// 其他不固定的键放到数组里避免索引签名
extraProperties?: SensorKV[];
}
interface Reported {
properties: SensorProperties;
event_time: string | null;
}
interface Desired {
properties: null | SensorKV[]; // 如果 desired 是可变键集合,用数组表示
event_time: string | null;
}
interface ShadowEntry {
service_id: string;
desired: Desired;
reported: Reported;
version: number;
}
interface RoomData {
device_id: string;
shadow: ShadowEntry[];
}
@Entry
@Component
struct Room {
@State message: string = 'Hello World'
@State temperature:number = 0
@State humidity:number = 0
@State token:string =''
// 指定具体类型并用简单初值(避免复杂字面量在装饰器处)
@State roomData: RoomData = {
device_id: '',
shadow: []
}
build() {
Column() {
Text("温度" + (this.roomData?.shadow?.[0]?.reported?.properties?.temperature ?? "加载中"))
Text("湿度" + (this.roomData?.shadow?.[0]?.reported?.properties?.humidity ?? "加载中"))
}
.height('100%').width('100%').justifyContent(FlexAlign.Center)
}
async aboutToAppear(){
// 在生命周期中注入示例数据(遵循上面定义的类型)
this.roomData = {
device_id: "68baaa7dd582f200184c27fa_0002",
shadow: [
{
service_id: "sensor",
desired: {
properties: null,
event_time: null
},
reported: {
properties: {
temperature: 35.6,
humidity: 15.2,
extraProperties: [
{ name: "co2", value: 400 },
{ name: "light", value: 123 }
]
},
event_time: "2025-01-15T08:26:52Z"
},
version: 0
}
]
};
await this.requestToken();
// 建议间隔不要太短,5s 比 1s 更稳健
setInterval(() => {
this.getDeviceData()
}, 5000);
}
requestToken(){
httpRequest.request(
// 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
"https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens",//https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens
{
method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET
// 开发者根据自身业务需要添加header字段
header: {
'Content-Type': 'application/json'
},
// 当使用POST请求时此字段用于传递内容
extraData:{
"auth": {
"identity": {
"methods": [
"hw_ak_sk"
],
"hw_ak_sk": {
"access": {
"key": AK
},
"secret": {
"key": SK
}
}
},
"scope": {
"project": {
"name": "cn-east-4"
}
}
}
},
}, (err, data) => {
if (!err) {
// data.result为HTTP响应内容,可根据业务需要进行解析
console.info('Result:' + JSON.stringify(data.result));
console.info('code:' + JSON.stringify(data.responseCode));
this.token = data.header['x-subject-token'];
console.info("mytoken="+this.token);
// this.getDeviceData();
// data.header为HTTP响应头,可根据业务需要进行解析
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
} else {
console.info('error:' + JSON.stringify(err));
promptAction.showToast({
message: '网络错误'
})
}
// 取消订阅HTTP响应头事件
httpRequest.off('headersReceive');
// 当该请求使用完毕时,调用destroy方法主动销毁。
httpRequest.destroy();
}
);
}
getDeviceData(){
httpRequest.request(
// 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
'https://152261edc6.st1.iotda-app.cn-north-4.myhuaweicloud.com/v5/iot/'+projectId+'/devices/'+deviceId+'/shadow',
{
method: http.RequestMethod.GET, // 可选,默认为http.RequestMethod.GET
// 开发者根据自身业务需要添加header字段
header: {
'Content-Type': 'application/json',
'X-Auth-Token':this.token
},
// 当使用POST请求时此字段用于传递内容
extraData:{
},
}, (err, data) => {
if (!err) {
// data.result为HTTP响应内容,可根据业务需要进行解析
console.info('Result:' + JSON.stringify(data.result));
console.info('code:' + JSON.stringify(data.responseCode));
this.roomData = JSON.parse(data.result.toString())
// data.header为HTTP响应头,可根据业务需要进行解析
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
} else {
console.info('error:' + JSON.stringify(err));
promptAction.showToast({
message: '网络错误'
})
}
// 取消订阅HTTP响应头事件
httpRequest.off('headersReceive');
// 当该请求使用完毕时,调用destroy方法主动销毁。
httpRequest.destroy();
}
);
}
}
2 回复
DevEco Studio 5.0运行连接华为云物联网平台代码显示网络错误,主要原因包括:
- 网络配置问题:设备未接入互联网,或防火墙、代理设置阻止了连接。
- 平台配置错误:设备接入信息(如产品ID、设备ID、密钥)填写不正确。
- SDK或依赖问题:项目使用的IoT Device SDK版本与鸿蒙API版本不兼容,或依赖未正确同步。
- 证书问题:在需要双向认证的场景下,设备证书可能未正确配置或已过期。
- 代码逻辑错误:连接代码中的时序、参数或回调处理可能存在缺陷。
根据你提供的代码,网络错误可能由以下几个原因导致:
-
网络权限未配置:这是最常见的原因。在
module.json5文件中,必须声明ohos.permission.INTERNET权限。{ "module": { "requestPermissions": [ { "name": "ohos.permission.INTERNET" } ] } } -
AK/SK 未正确填写:代码中
AK和SK变量为空字符串。你需要填入从华为云IAM获取的有效访问密钥。 -
项目区域不匹配:
- Token请求:代码中
scope.project.name设置为"cn-east-4"。 - 设备数据请求:URL 包含
cn-north-4。 请确保这两个区域与你华为云物联网平台项目的实际所在地域一致。
- Token请求:代码中
-
模拟器/真机网络问题:DevEco Studio的Previewer预览器不支持网络请求。必须在本地模拟器或真机上运行,并确保其网络畅通。
-
HTTP请求销毁过早:你在每个请求的回调中都调用了
httpRequest.destroy(),但httpRequest是全局变量。在getDeviceData被定时器重复调用时,可能前一个请求已被销毁导致异常。建议将httpRequest的生命周期管理移至组件内或避免重复销毁。 -
服务器地址或设备ID错误:请确认物联网平台设备的详情页中的访问地址和设备ID与代码中的
projectId、deviceId及URL完全匹配。
建议按以下顺序排查:
- 首先检查
module.json5的权限配置。 - 在真机或模拟器上运行,查看
console.info('error:' + JSON.stringify(err));输出的具体错误信息。 - 确保AK/SK、项目区域、设备信息完全正确。

