HarmonyOS 鸿蒙Next中接口请求时入参固定参数及格式问题

HarmonyOS 鸿蒙Next中接口请求时入参固定参数及格式问题 描述: 接口入参时会涉及到固定的参数部分,如IP地址,设备ID,设备型号等,我们希望将这些固定参数放到BaseRequest中,功能接口入参类(如:LoginRequest)集成BaseRequest, 这样在请求时只需要传入跟功能相关的参数即可,但是发现在使用子请求类时,无法直接继承BaseRequest的固定参数,请问有没有什么解决方法?或者有没有更合理接口入参方式?

3 回复

可参考以下demo:

import axios, { AxiosError, AxiosResponse } from '@ohos/axios';

class baseRequest {

  reqIP: string = ''

  reqDeviceId: string = ''

  reqDeviceModel: string = ''

}

class LoginRequest extends baseRequest {

  name: string

  pwd: string

  constructor(name: string, pwd: string) {
    super()
    this.name = name
    this.pwd = pwd
  }

}

export function axiosGet(url: string, params: baseRequest): Promise<string> {
  return new Promise((resolve, reject) => {
    console.info('test info request url:' + JSON.stringify(url))
    params.reqIP = 'xxx'
    params.reqDeviceId = 'xxx'
    params.reqDeviceModel = 'xxx'
    // 发送一个get请求(默认请求方式)
    axios.get<string, AxiosResponse<string>, null>(url,
      { params: params, headers: { 'Content-Type': 'application/json' }, })
      .then((response: AxiosResponse) => {
        console.info("test info result:" + JSON.stringify(response.data));
        resolve(response.data)
      })
      .catch((error: AxiosError) => {
        console.error("test info result:" + error.message);
        reject(error)
      });
  })
}

axiosGet('', new LoginRequest('name', 'pwd'))

如果赋值到baseRequest 里,同样每个接口都会有这些参数。如需要赋值可以在baseRequest 属性定义时直接赋值;或者通过构造器传值进来赋值,传值后进行非空判断赋值。

更多关于HarmonyOS 鸿蒙Next中接口请求时入参固定参数及格式问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,接口请求时的入参固定参数及格式通常由API文档定义。常见的固定参数包括appIddeviceIdtimestamp等,用于标识应用、设备和请求时间。这些参数通常以JSON格式传递,例如:

{
  "appId": "com.example.app",
  "deviceId": "1234567890",
  "timestamp": "2023-10-01T12:00:00Z",
  "data": {
    "key1": "value1",
    "key2": "value2"
  }
}

其中,data部分为业务相关参数。请求头中可能需要包含Content-Type: application/jsonAuthorization等字段。具体参数和格式需参考API文档。

在HarmonyOS鸿蒙Next中,接口请求的入参通常需要遵循固定的参数和格式要求。首先,确定API文档中规定的必填参数,并确保其类型和值符合要求。入参一般以JSON格式传递,需使用JSONObjectJSONArray进行封装。例如:

JSONObject params = new JSONObject();
params.put("key1", "value1");
params.put("key2", 123);

通过HttpURLConnectionOkHttp等工具发送请求时,需将参数设置为请求体或附加到URL中。确保遵循API的编码规范,如Content-Type: application/json

回到顶部