马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
实现http请求,在ArkTS中我们可以直接使用http如下代码
- import http from '@ohos.net.http'
- @Entry
- @Component
- struct HttpPage {
- @State message: string = 'Hello World'
- build() {
- Column({space:20}) {
- Row(){
- Button('发送http请求')
- .onClick(()=>{
- let httpRequest = http.createHttp();
- httpRequest.request(
- 'http://localhost:8018/device/getDeviceDetail',
- {
- method:http.RequestMethod.POST,
- extraData:{
- sn:'1001'
- }
- }
- )
- .then(resp=>{
- console.log("resp=>",JSON.stringify(resp))
- if(resp.responseCode === 200){
- console.log(resp.result.toString())
- }
- }).catch(err=>{
- console.log('请求错误err=>',err)
- })
- })
- }
-
- }
- .width('100%')
- .height('100%')
- }
- }
复制代码 实现axios我们需要使用一个第三方工具
2. 解压文件,进入“ohpm/bin”目次,打开下令行工具,实行如下指令初始化ohpm
Windows情况下实行:
init.bat
如果init.bat不可以使用./init.bat
3. 将ohpm配置到情况变量中。
- export OHPM_HOME=/home/xx/Downloads/ohpm #本处路径请替换为ohpm的安装路径
- export PATH=${OHPM_HOME}/bin:${PATH}
复制代码 4. 安装完成后,实行ohpm -v 在终端中显示版本号安装成功
5. 安装axios库,在链接
OpenHarmony三方库中央仓
找到@ohos/axios
6. 在当前项目终端目次下实行
OpenHarmony三方库中央仓需要网络权限,在module.json5文件中将以下代码配置到module中
- "requestPermissions": [
- {
- "name": 'ohos.permission.INTERNET'
- }
- ],
复制代码 新建一个.ets文件,如下代码写入
- import http from '@ohos.net.http'
- import axios from '@ohos/axios'
- @Entry
- @Component
- struct HttpPage {
- @State message: string = 'Hello World'
- build() {
- Column({space:20}) {
- Row(){
- Button('发送http请求')
- .onClick(()=>{
- let httpRequest = http.createHttp();
- httpRequest.request(
- 'http://localhost:8018/device/getDeviceDetail',//请求路径http://localhost:8018/device/getDeviceDetail
- {
- method:http.RequestMethod.POST,
- extraData:{
- sn:'1001'
- }
- }
- )
- .then(resp=>{
- console.log("resp=>",JSON.stringify(resp))
- if(resp.responseCode === 200){
- console.log(resp.result.toString())
- }
- }).catch(err=>{
- console.log('请求错误err=>',err)
- })
- })
- }
- Row(){
- Button('发送axios请求')
- .onClick(()=>{
- axios.post(
- 'http://localhost:8018/device/getDeviceDetail',
- {
- sn:'1001'
- }
- ).then(response=>{
- console.log("response=>",JSON.stringify( response))
- }).catch(err=>{
- console.log('err=>',err)
- })
- })
- }
- }
- .width('100%')
- .height('100%')
- }
- }
复制代码 就可以实现axios请求了,当然后续可以将http和axios封装成一个单独的文件,方便后续项目开发的接口请求
注意:网络请求接口需要替换成本身项目标相应接口,本文中接口地点为当地地点。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |