arkts发送网络请求
- 方法1
使用官方提供的http模块
// 引入包名
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
安装
ohpm install @ohos/axios
申请权限
在module.json5里面添加权限申请
"requestPermissions": [
{
"name": "ohos.permission.INTERNET",
"reason": "$string:network_reson"
},
]
使用示例
get请求
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请求
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));
});
二次封装
创建工具类方法
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请求
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请求
Http.post<LoginResponse>("/auth/login", this.form)
.then((res) => {
console.log(JSON.stringify(res));
})
文件上传
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)
9 0
评论 (0)
请先登录后再评论
暂无评论