arkts发送网络请求

arkts发送网络请求

  • 方法1
    使用官方提供的http模块
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    // 引入包名
    import http from '@ohos.net.http';
    import { BusinessError } from '@ohos.base';

    // 每一个httpRequest对应一个HTTP请求任务,不可复用
    let httpRequest = http.createHttp();
    // 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
    // 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。
    httpRequest.on('headersReceive', (header) => {
    console.info('header: ' + JSON.stringify(header));
    });
    httpRequest.request(
    // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
    "EXAMPLE_URL",
    {
    method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET
    // 开发者根据自身业务需要添加header字段
    header: {
    'Content-Type': 'application/json'
    },
    // 当使用POST请求时此字段用于传递请求体内容,具体格式与服务端协商确定
    extraData: "data to send",
    expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型
    usingCache: true, // 可选,默认为true
    priority: 1, // 可选,默认为1
    connectTimeout: 60000, // 可选,默认为60000ms
    readTimeout: 60000, // 可选,默认为60000ms
    usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定
    usingProxy: false, // 可选,默认不使用网络代理,自API 10开始支持该属性
    }, (err: BusinessError, data: http.HttpResponse) => {
    if (!err) {
    // data.result为HTTP响应内容,可根据业务需要进行解析
    console.info('Result:' + JSON.stringify(data.result));
    console.info('code:' + JSON.stringify(data.responseCode));
    // data.header为HTTP响应头,可根据业务需要进行解析
    console.info('header:' + JSON.stringify(data.header));
    console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
    // 当该请求使用完毕时,调用destroy方法主动销毁
    httpRequest.destroy();
    } else {
    console.error('error:' + JSON.stringify(err));
    // 取消订阅HTTP响应头事件
    httpRequest.off('headersReceive');
    // 当该请求使用完毕时,调用destroy方法主动销毁
    httpRequest.destroy();
    }
    }
    );
  • 方法2
    使用第三方包,比如@ohos/axios或者@nutpi/request,本文使用axios

安装

1
ohpm install @ohos/axios

申请权限

在module.json5里面添加权限申请

1
2
3
4
5
6
"requestPermissions": [
{
"name": "ohos.permission.INTERNET",
"reason": "$string:network_reson"
},
]

使用示例

get请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import axios from '@ohos/axios'
interface userInfo{
id: number
name: string,
phone: number
}

// 向给定ID的用户发起请求
axios.get<userInfo, AxiosResponse<userInfo>, null>('/user?ID=12345')
.then((response: AxiosResponse<userInfo>)=> {
// 处理成功情况
console.info("id" + response.data.id)
console.info(JSON.stringify(response));
})
.catch((error: AxiosError)=> {
// 处理错误情况
console.info(JSON.stringify(error));
})
.then(()=> {
// 总是会执行
});

// 上述请求也可以按以下方式完成(可选)
axios.get<userInfo, AxiosResponse<userInfo>, null>('/user', {
params: {
ID: 12345
}
})
.then((response:AxiosResponse<userInfo>) => {
console.info("id" + response.data.id)
console.info(JSON.stringify(response));
})
.catch((error:AxiosError) => {
console.info(JSON.stringify(error));
})
.then(() => {
// 总是会执行
});

// 支持async/await用法
async function getUser() {
try {
const response:AxiosResponse = await axios.get<string, AxiosResponse<string>, null>(this.getUrl);
console.log(JSON.stringify(response));
} catch (error) {
console.error(JSON.stringify(error));
}
}

post请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
interface user {
firstName: string,
lastName: string
}
axios.post<string, AxiosResponse<string>, user>('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then((response: AxiosResponse<string>) => {
console.info(JSON.stringify(response));
})
.catch((error) => {
console.info(JSON.stringify(error));
});

二次封装

创建工具类方法

utils/request.ets

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from '@ohos/axios'
import { PreferencesManager } from '@yue/preferences_manager'
import router from '@ohos.router';

const instance = axios.create({
baseURL: 'https://exapmle.com/api',
timeout: 30000,
headers: { 'client': 'app' }
});
// 添加请求拦截器
instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
// 获取token
const token = PreferencesManager.defManager.get("access_token", "")
if (token) {
config.headers.Authorization = 'Bearer ' + token
}
return config;
}, (error: AxiosError) => {
// 对请求错误做些什么
return Promise.reject(error);
});


// 添加响应拦截器
instance.interceptors.response.use((response: AxiosResponse) => {
// 对响应数据做点什么
return response.data
}, (error: AxiosError) => {
if (error.response?.status === 401) {
router.pushUrl({
url: 'pages/Login'
})
}
// 对响应错误做点什么
return Promise.reject(error);
});

export class HTTP {
// 全部请求
static request<T>(config: InternalAxiosRequestConfig): Promise<T> {
return instance<null, T>(config)
}

//Get请求
static get<T>(url: string, params?: object): Promise<T> {
return instance.get<null, T>(url, { params })
}

//Post请求
static post<T>(url: string, data?: object, config?: object): Promise<T> {
return instance.post<null, T>(url, data, config)
}

//Put请求
static put<T>(url: string, data?: object): Promise<T> {
return instance.put<null, T>(url, data)
}

//Delete请求
static delete<T>(url: string, data?: object): Promise<T> {
return instance.delete<null, T>(url, { data })
}
}

export default HTTP

使用示例

get请求

1
2
3
4
5
6
7
8
9
10
11
import { HTTP } from '../utils/request'
import { AxiosResponse } from '@ohos/axios'

HTTP.get<Array<Album>>("/gateway/myGalleryList")
.then(res => {
this.albumList = res
if (res.length) {
this.galleryId = res[0].id
this.getImageList()
}
})

post请求

1
2
3
4
Http.post<LoginResponse>("/auth/login", this.form)
.then((res) => {
console.log(JSON.stringify(res));
})

文件上传

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const buffer = new ArrayBuffer(stat.size);
fs.readSync(file.fd, buffer);

const formData = new FormData()
formData.append('file', buffer);

await HTTP.post<UploadResp>('/gateway/upload', formData, {
headers: {
mtextra: encodeURIComponent(JSON.stringify(params)),
ctime: stat.ctime * 1000,
devicename: deviceInfo.productModel,
filename: file.name,
'Content-Type': 'multipart/form-data'
} as Header
} as Config)

arkts发送网络请求
https://mengluo.com/2025/04/18/arkts发送网络请求/
作者
梦落
发布于
2025年4月18日
许可协议