kit.NetworkKit的http模块实践
开发鸿蒙应用,网络请求少不了,在ArkTs语言中,可使用原生的@kit.NetworkKit中的http模块来实现GET或POST请求,当然也可以使用axios模块。初次在鸿蒙应用中使用http模块,可能会报如下错误:
To use this API, you need to apply for the permissions: ohos.permission.INTERNET <ArkTSCheck>
这是因为应用没有获得网络请求权限,需要在/ProjectDir/entry/src/main/module.json5中配置网络请求权限,添加如下代码实现:
"requestPermissions": [ { "name": "ohos.permission.INTERNET" } ],
添加配置代码后,会提示Core configuration attributes have changed since last project sync,A project sync may be necessary for the IDE to work properly,点击Sync Now即可
完整的module.json5配置示例如下:
{ "module": { "name": "entry", "type": "entry", "description": "$string:module_desc", "mainElement": "EntryAbility", "deviceTypes": [ "phone", "tablet", "2in1" ], "deliveryWithInstall": true, "installationFree": false, "pages": "$profile:main_pages", "requestPermissions": [ { "name": "ohos.permission.INTERNET" } ], "abilities": [ { "name": "EntryAbility", "srcEntry": "./ets/entryability/EntryAbility.ets", "description": "$string:EntryAbility_desc", "icon": "$media:layered_image", "label": "$string:EntryAbility_label", "startWindowIcon": "$media:startIcon", "startWindowBackground": "$color:start_window_background", "exported": true, "skills": [ { "entities": [ "entity.system.home" ], "actions": [ "action.system.home" ] } ] } ], "extensionAbilities": [ { "name": "EntryBackupAbility", "srcEntry": "./ets/entrybackupability/EntryBackupAbility.ets", "type": "backup", "exported": false, "metadata": [ { "name": "ohos.extension.backup", "resource": "$profile:backup_config" } ], } ] } }