金歌 发表于 2024-10-22 11:23:49

基于@ohos/axios的网络请求能力

简介
Axios是一个基于promise的网络请求库,可以运行node.js和欣赏器中。基于Axios原库v1.3.4GitHub版本举行适配,使其可以运行在OpenHarmony并相沿其现有用法和特性。


[*]http请求。
[*]request和 response拦截器。
[*]转换request和response的data数据。
[*]主动转换JSON data数据。
下载与安装三方库
// 在终端cd到需要使用三方库的module 运行下面命令
ohpm install @ohos/axios 须要使用到的权限:ohos.permission.INTERNET。
场景一:使用axios发送通例请求
如:axios.get<T = any, R = AxiosResponse, D = any>(url)


[*]R: 是相应体的范例。当服务器返回一个相应时,相应体通常是一个JSON对象。R就是这个JSON对象的范例。默认情况下,R是AxiosResponse,这意味着相应体是一个AxiosResponse对象,它的data属性是T范例的
[*]D: 是请求参数的范例。当发送一个GET请求时,大概会在URL中添加一些查询参数。D就是这些查询参数的范例。参数为空情况下,D是null范例。
发送一个get请求获取服务器端的JSON字符串
https://i-blog.csdnimg.cn/blog_migrate/80f02d5e33a3c2f7889c94939596813a.png
使用axios来获取,performanceTiming盘算HTTP请求的各个阶段所花费的时间。
axios.get<string, AxiosResponse<string>, null>(this.getUrl, {}).then((res: AxiosResponse) => {
  this.status =  res.status;
  this.message = JSON.stringify(res.data);
  this.performanceTiming = JSON.stringify(res.performanceTiming) : '';
}).catch((err: AxiosError) => {
  this.status = '';
  this.message = err.message;
}) 将请求效果表现。
https://i-blog.csdnimg.cn/blog_migrate/12febe7470e361fd657a586f5e5731f0.png
使用axios为服务端的JSON添加data数据这个时间使用POST请求。
axios.post<T = any, R = AxiosResponse, D = any>(url)
T: 是相应数据范例。当发送一个 POST 请求时,客户端大概会收到一个 JSON 对象。T 就是这个 JSON 对象的范例。默认情况下,T 是 any,这意味着可以接收任何范例的数据。
axios<InfoModel, AxiosResponse<InfoModel>, IdModel>({
  url: this.postUrl,
  method: 'POST',
  data: {
    id: 592,
    name: 'zxing',
    gitUrl: 'https://gitee.com/openharmony-tpc/zxing',
  },
}).then((res: AxiosResponse<InfoModel>) => {
  this.status =  res.status;
  this.message = JSON.stringify(res.data);
  this.performanceTiming = JSON.stringify(res.performanceTiming) : '';
}).catch((err: AxiosError) => {
  this.status = '';
  this.message = err.message;
}) 这里可以看到服务器端的data数据上传乐成。
https://i-blog.csdnimg.cn/blog_migrate/40b50a1e17c6e40e843666789c988297.png
错误处置惩罚
// 错误处理示例代码
axios.get<string, AxiosResponse<string>, null>('url').catch((error: AxiosError)=> {
  console.log(JSON.stringify(error.message));
  console.log(JSON.stringify(error.code));
  console.log(JSON.stringify(error.config));
}); 参考文档:HTTP错误码。
场景二:请求拦截器与相应拦截器的使用
发送一段带设置的请求
let config: AxiosRequestConfig= {
  url: 'https://xxx.com',
  method: 'POST',
  headers: {
    'Accept-Language': 'zh-cn',
    'bfw-ctrl' : 'json',
    'Content-Type': 'application/json',
    'cookies': 'sad',
  },
  // timeout指定请求超时的毫秒数(0 表示无超时时间)
  // 如果请求超过timeout的时间,请求将被中断
  timeout: 1000,
  // connectTimeout指定请求连接服务器超时的毫秒数(0 表示无超时时间)
  // 如果请求连接服务器超过connectTimeout的时间,请求将被中断
  connectTimeout: 60000,
  // data是作为请求主体被发送的数据
  // 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
  data: {
    'common': {
      'view': 'good'
    }
  }
} 请求拦截器
在请求发送进步行须要操纵处置惩罚,比方设置请求头,获取请求设置或者修改,设置超时时间等,相称于是对每个接口里雷同操纵的一个封装。
// 添加请求拦截器
axios.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  // 对超时时间进行修改
  config.timeout=100,
  config.connectTimeout: 60000,
  // 对请求config进行输出
  console.log('test=='+ JSON.stringify(config.headers['Content-Type']))
  console.log('test=='+ JSON.stringify(config.headers['cookies']))
  console.log('test=='+ JSON.stringify(config.data))
  return config;
}, (error: AxiosError) => {
  // 对请求错误做些什么
  return Promise.reject(error);
}); 相应体结构
{
  // data由服务器提供的响应
  data: {},
  // status来自服务器响应的 HTTP 状态码
  status: 200,
  // statusText来自服务器响应的 HTTP 状态信息
  statusText: 'OK',
  // headers是服务器响应头
  // 所有的header名称都是小写,而且可以使用方括号语法访问
  // 例如: response.headers['content-type']
  headers: {},
  // config是axios请求的配置信息
  config: {},
  // request是生成此响应的请求
  request: {}
  // performanceTiming计算HTTP请求的各个阶段所花费的时间
  performanceTiming: http.PerformanceTiming
} 新增performanceTiming的一些属性定义。
相应拦截器
同理,相应拦截器也是如此功能,只是在请求得到相应之后,对相应体的一些处置惩罚。
// 添加响应拦截器
axios.interceptors.response.use((response: AxiosResponse)=> {
  // 对响应数据做点什么
  console.log('test=='+ JSON.stringify(response.performanceTiming))
  return response;
}, (error: AxiosError)=> {
  // 对响应错误做点什么
  return Promise.reject(error);
}); 场景三:上传下载文件
上传文件
上传示例


[*]上传范例支持uri和ArrayBuffer,uri支持“internal”协议范例和沙箱路径,仅支持"internal"协议范例,"internal://cache/"为必填字段,示例: internal://cache/path/to/file.txt;沙箱路径示例:cacheDir + '/hello.txt'
[*]上传参数context:当uri为沙箱路径,无需传参context;若uri为“internal”协议范例,必须传参context
FormData 对象介绍
FormData可以将表单字段的键值对以键值对的方式添加,同时也支持添加文件,在文件上传的场景中,我们可以使用FormData对象来收集表单数据,包罗文件和其他文本字段,然后将其发送到后端服务器。
Axios可以通过FormData对象上传文件,在FormData中追加文件,我们须要用POST方法,再设置headers,须要这个欣赏器才知道是表单。
import axios from '@ohos/axios'
import { FormData } from '@ohos/axios'
import fs from '@ohos.file.fs';
 
// ArrayBuffer
let formData = new FormData()
let cacheDir = getContext(this).cacheDir
try {
  // 写入
  let path = cacheDir + '/test.txt';
  let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE)
  fs.writeSync(file.fd, 'hello, world'); // 以同步方法将数据写入文件
  fs.fsyncSync(file.fd); // 以同步方法同步文件数据。
  fs.closeSync(file.fd);
  // 读取
  let file2 = fs.openSync(path, 0o2);
  let stat = fs.lstatSync(path);
  let buf2 = new ArrayBuffer(stat.size);
  fs.readSync(file2.fd, buf2); // 以同步方法从流文件读取数据。
  fs.fsyncSync(file2.fd);
  fs.closeSync(file2.fd);
  formData.append('file', buf2);
} catch (err) {
  console.info('err:' + JSON.stringify(err));
}
// 发送请求
axios.post<string, AxiosResponse<string>, FormData>(this.downloadUrl, formData, {
  headers: { 'Content-Type': 'multipart/form-data' },
  context: getContext(this),
}).then((res: AxiosResponse) => {
  console.info("result" + JSON.stringify(res.data));
  // PerformanceTiming网络性能监测数据
  this.status = res ? res.status : '';
  this.message = res ? JSON.stringify(res.data) : '';
  this.performanceTiming = res ? JSON.stringify(res.performanceTiming) : "";
}).catch((error: AxiosError) => {
  console.error("error:" + JSON.stringify(error));
}) 这里模拟前后端交互,下方为服务端模拟代码,其实就是一个上传的方法,首先通过MultipartFile接收文件。
@PostMapping("/upload")
public Result upload(@RequestParam("file") MultipartFile file) {
  if (file.isEmpty()) {
    return Result.fail('文件为空,请选择一个文件上传。');
  }
  try {
    // 获取文件名
    String name = file.getOriginalFilename();
    // 获取文件大小
    long size = file.getSize();
    // 获取文件类型
    String type = file.getContentType();
    // 获取文件的字节
    byte[] bytes = file.getBytes();
    // ......
    Map<String, Object> map = new HashMap<>();
    map.put('文件名', name);
    map.put('文件类型', type);
    map.put('文件大小', size);
    map.put('文件内容', subBytes);
    return  Result.success(map);
  } catch (Exception e) {
    return Result.fail('文件上传失败:' + e.getMessage());
  }
} 下载文件
下载文件时,假如filePath已存在该文件则下载失败,下载之前须要先删除文件。
let filePath = getContext(this).cacheDir + '/test.txt'
// 下载。如果文件已存在,则先删除文件。
try {
  fs.accessSync(filePath);
  fs.unlinkSync(filePath);
} catch (err) {
}
axios({
  // url: this.downloadUrl
  url: '',
  method: 'get',
  filePath: filePath
}).then((res) => {
  console.info('result: ' + JSON.stringify(res.data));
}).catch((error) => {
  console.error('error:' + JSON.stringify(error));
})  

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 基于@ohos/axios的网络请求能力