HarmonyOS development: callback to implement network interception

Preface

A network library based on http encapsulation, there is a knowledge point in it. During initialization, you can set up request header interception and interception of information after request errors. The specific cases are as follows:

et.getInstance().init({
  
  netErrorInterceptor: new MyNetErrorInterceptor(), //设置全局错误拦截,需要自行创建,可在这里进行错误处理
  netHeaderInterceptor: new MyNetHeaderInterceptor(), //设置全局头拦截器,需要自行创建

})

When an error occurs in a request, the error information will be sent back to the custom netErrorInterceptor. Similarly, when a request is initiated, if there is a request header interception, netHeaderInterceptor will be executed first, the header parameters will be passed, and then the request and request mode will be executed. as follows:

What we need to know is that in the development of Hongmeng, unlike okhttp in Android, which provides us with certain interceptors, the http system API in Hongmeng does not provide any interceptor concept, which leads to us If you want to implement unified request header interception or unified error handling, you need to define it yourself.

How to implement it is to perform callback processing just like the flow chart above.

Initialization passed in

We can set the corresponding interception through global initialization. Of course, it is not limited to these two interceptions. MyNetErrorInterceptor is a custom error interception object and needs to be inheritedNetErrorInterceptor. NetHeaderInterceptor, MyNetHeaderInterceptor is a custom request header interceptor object, inherited from

Net.getInstance().init({
  
  netErrorInterceptor: new MyNetErrorInterceptor(), //设置全局错误拦截,需要自行创建,可在这里进行错误处理
  netHeaderInterceptor: new MyNetHeaderInterceptor(), //设置全局头拦截器,需要自行创建

})

It should be noted that under the same module, we can use interfaces to create our interception objects. If you want to package har, or different modules, there is a problem using interfaces to export. How to solve it? Use abstract classes as To intercept the object, the code is as follows:

NetErrorInterceptor object inherited by MyNetErrorInterceptor:

import { NetError } from '../error/NetError';

/**
 * AUTHOR:AbnerMing
 * DATE:2023/9/12
 * INTRODUCE:全局异常拦截
 * */
export abstract class NetErrorInterceptor {
  abstract httpError(error: NetError)
}

NetHeaderInterceptor object inherited by MyNetHeaderInterceptor:

import { HttpHeaderOptions } from '../model/HttpHeaderOptions';

/**
 * AUTHOR:AbnerMing
 * DATE:2023/9/13
 * INTRODUCE:全局头参数拦截
 * */

export abstract class NetHeaderInterceptor {
  abstract getHeader(options: HttpHeaderOptions): Promise<Object>
}

Tool class receiving

After the global initialization is set, we need to receive it in the Net tool class. After receiving the value and assigning it to the member variable, it will be exposed through the method to facilitate subsequent calls.

private mNetErrorInterceptor: NetErrorInterceptor //全局错误拦截
private mNetHeaderInterceptor: NetHeaderInterceptor //全局头拦截器

  /*
  * Author:AbnerMing
  * Describe:初始化
  */
  init(options: NetOptions) {
    this.mNetErrorInterceptor = options.netErrorInterceptor
    this.mNetHeaderInterceptor = options.netHeaderInterceptor
  }


  /*
  * Author:AbnerMing
  * Describe:获取全局错误拦截
  */
  getNetError(): NetErrorInterceptor {
    return this.mNetErrorInterceptor
  }

  /*
  * Author:AbnerMing
  * Describe:获取全局头拦截器
  */
  getNetHeaderInterceptor(): NetHeaderInterceptor {
    return this.mNetHeaderInterceptor
  }

for use

In the first two steps, the action has been implemented. How to trigger this action, then you need to call it, that is, call the implementation method, call back the data, get the set object through getNetError or getNetHeaderInterceptor, and make a non-empty judgment. Just call the function in the object.

1. Request header interception call

Note: This interception is set before the request is initiated. If intercepted, you must wait for the header parameters to be executed.

if (Net.getInstance().getNetHeaderInterceptor() != null) {
      //需要拦截头参数了
      Net.getInstance()
        .getNetHeaderInterceptor()
        .getHeader({
          url: this.getUrl(),
          method: this.getMethod(),
          params: this.getParams(),
          header: this.getHeaders()
        })
        .then((header) => {
          //发起请求
          this.setHeaders(header)
          this.doRequest(
            httpRequest,
            success, error,
            isReturnString, isReturnData)
        })
        .catch(() => {
          //发起请求
          this.doRequest(
            httpRequest,
            success, error,
            isReturnString, isReturnData)
        })
    }

2. Error interception call

Callback when request error occurs.

      //全局回调错误信息
      if (Net.getInstance().getNetError() != null) {
        Net.getInstance().getNetError().httpError(new NetError(err.code, NetError.responseError(err.code)))
      }

Information return

How to get the returned data? We have already passed it in in the initialization settings in the first step, and you can get it in the implementation method.

1. Request header interception object

import { HttpHeaderOptions, NetHeaderInterceptor } from '@app/net'

class MyNetHeaderInterceptor implements NetHeaderInterceptor {
  getHeader(options: HttpHeaderOptions): Promise<Object> {
    //进行签名加密,设置请求头等操作
    return null
  }
}

2. Request error interception object

import { NetError } from '@app/net/src/main/ets/error/NetError';
import { INetErrorInterceptor } from '@app/net/src/main/ets/interceptor/INetErrorInterceptor';

export class MyNetErrorInterceptor implements INetErrorInterceptor {
  httpError(error: NetError) {
    //这里进行拦截错误信息

  }
}

Related summary

Some veterans may question their souls, why do we need to perform a callback before requesting? Doesn’t http provide subscription to Header events? You can perform callbacks here. Indeed, before initiating a request, you can use the following code to modify the request header. By subscribing to parameters, you can get some information about the request header parameters. You can also perform request header callbacks, which is interception.

httpRequest.on('headerReceive', (err, data) => {
    if (!err) {
        console.info('header: ' + JSON.stringify(data));
    } else {
        console.info('error:' + JSON.stringify(err));
    }
});

However, there is an exception, that is, if there are time-consuming operations in your request header callback object, such as signature encryption, etc., then when you perform a callback in the subscription, it will happen that the request has been initiated, but the request header parameters If it is not added, it means that the request is out of sync. Therefore, in this case, you must wait until the request header parameters are executed before making a request, and you cannot set it in the subscription.

Guess you like

Origin blog.csdn.net/qq_39312146/article/details/134935353
Recommended