HarmonyOS鸿蒙Next中API22 @kit.NetworkKit网络拦截器抛出unsupported body type

HarmonyOS鸿蒙Next中API22 @kit.NetworkKit网络拦截器抛出unsupported body type 我在鸿蒙API22上进行开发的时候用到了网络拦截器这个API,但是在实际使用的时候会发现如果在intercepor里面加入了网络请求和await async的function,底层的http_interceptor会有报错erceptor Interceptor

cke_1733.png

但是问题是单独注释掉await async的函数或者http请求就不会有这种错误。

import { http } from '[@kit](/user/kit).NetworkKit';
import { hilog } from '[@kit](/user/kit).PerformanceAnalysisKit';
import { FooInterceptor } from '../FooInterceptor';

let TAG = "DebugNetHttp1111"

@Entry
@Component
struct Index {
  @State message: string = '???';

  build() {
    Row() {
      Text(this.message)
      Button("点击发送网络请求并且拦截").onClick(async () => {
          await this.request()
        })
    }
    .height('100%')
    .width('100%')
  }

  private async request():Promise<void>{
    let TAG = "DebugNetHttp1111"
    const httpRequest = http.createHttp();
    try {
      const interceptor = new FooInterceptor();
      const interceptorChain = new http.HttpInterceptorChain();
      let success = interceptorChain.addChain([interceptor])
      success = success && interceptorChain.apply(httpRequest)
      if (!success) {
        hilog.error(0, TAG, " Cannot build httpRequest as interceptor error")
      }
    } catch (e) {
      hilog.error(0, TAG, `Interceptor chain add failed: code=${e.code}, message=${e.message}`)
    }

    try {
      const response = await httpRequest.request("https://approov.io", {
        method: http.RequestMethod.GET,
        expectDataType: http.HttpDataType.STRING,
      });
      const statusCode = response.responseCode as number;
      const status = `Http status code ${statusCode}`;
      if (statusCode >= 200 && statusCode < 300) {
        hilog.debug(0, TAG, ' call successful');
      } else {
        hilog.debug(0, TAG, ' call unsuccessful');
      }
    } catch (error) {
      const err = error as Error;
      this.message  = `Request failed: ${err?.message ?? JSON.stringify(error)}`;

    } finally {
      httpRequest.destroy();
    }
  }
}
import { http } from '[@kit](/user/kit).NetworkKit'
import { hilog } from '[@kit](/user/kit).PerformanceAnalysisKit';

class TestClass{
  public static async asyncTest(input:string):Promise<string>{
    return "1"
  }
}

export class FooInterceptor implements  http.HttpInterceptor {
  interceptorType: http.InterceptorType = http.InterceptorType.INITIAL_REQUEST;
  private readonly TAG = 'Interceptor'


  async interceptorHandle(requestContext: http.HttpRequestContext, rspContext: http.HttpResponse): Promise<http.ChainContinue> {
    await TestClass.asyncTest("3")
    const httpRequest2 = http.createHttp();
    try {
      const response = await httpRequest2.request('https://baidu.com', { //为了示例所以改成了百度,实际上是自己的项目
        method: http.RequestMethod.GET,
        header: {},
        expectDataType: http.HttpDataType.STRING,
      });
      const statusCode = response.responseCode as number;
      if (statusCode >= 200 && statusCode < 300) {
        hilog.debug(0, this.TAG, 'Hello call successful');
        interface ResponseHello {
          message: string;
        }
        hilog.warn(0, this.TAG, 'Hello call successful');
      } else {
        hilog.warn(0, this.TAG, 'Hello call unsuccessful');
      }
    } catch (error) {
      const err = error as Error;
      const msg = `Request failed: ${err?.message ?? JSON.stringify(error)}`;
      hilog.warn(0, this.TAG, msg);
    } finally {
      httpRequest2.destroy();
    }
    return true
  }


}

更多关于HarmonyOS鸿蒙Next中API22 @kit.NetworkKit网络拦截器抛出unsupported body type的实战教程也可以访问 https://www.itying.com/category-93-b0.html

10 回复

尊敬的开发者,您好,参照您的代码已复现问题。您这边可以尝试将TestClass.asyncTest调用注释后,最后return Promise.resolve(true),我这边测试操作后两个http请求都是成功的。

import { http } from '@kit.NetworkKit'
import { hilog } from '@kit.PerformanceAnalysisKit';

class TestClass{
  public static async asyncTest(input:string): Promise<string>{
    return "1"
  }
}

export class FooInterceptor implements  http.HttpInterceptor {
  interceptorType: http.InterceptorType = http.InterceptorType.INITIAL_REQUEST;
  private readonly TAG = 'Interceptor'

  async interceptorHandle(requestContext: http.HttpRequestContext, rspContext: http.HttpResponse): Promise<http.ChainContinue> {
    // let a = await TestClass.asyncTest("3")
    const httpRequest2 = http.createHttp();
    try {
      const response =await httpRequest2.request('https://baidu.com', { //为了示例所以改成了百度,实际上是自己的项目
        method: http.RequestMethod.GET,
        header: {},
        expectDataType: http.HttpDataType.STRING,
      });
      console.log(JSON.stringify(response))
      const statusCode = response.responseCode as number;
      if (statusCode >= 200 && statusCode < 300) {
        hilog.debug(0, this.TAG, 'Hello call successful');
        interface ResponseHello {
          message: string;
        }
        hilog.warn(0, this.TAG, 'Hello call successful');
      } else {
        hilog.warn(0, this.TAG, 'Hello call unsuccessful');
      }
    } catch (error) {
      const err = error as Error;
      const msg = `Request failed: ${err?.message ?? JSON.stringify(error)}`;
      hilog.warn(0, this.TAG, msg);
    } finally {
      console.log('destroy')
      httpRequest2.destroy();
    }
    return Promise.resolve(true);
  }
}

更多关于HarmonyOS鸿蒙Next中API22 @kit.NetworkKit网络拦截器抛出unsupported body type的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


是的, 注释掉之后是能成功的。这个TestClass.asyncTest的操作只是我原有逻辑里面的简化版本,所以在实际的业务开发里面绕不开。针对这个问题,我已经提单了,谢谢

好的开发者,您可关注后续对应工单的处理进展,有问题也可及时反馈。

拦截完返回。比如:return Promise.resolve(xxx);
PS:拦截器里新的http请求,走不走拦截器,注意跳出逻辑。

我试着在最后return Promise.resolve(true), 但是还是一样的现象,大佬能再帮忙看看吗?

  const msg = `Request failed: ${err?.message ?? JSON.stringify(error)}`;
  hilog.warn(0, this.TAG, msg);
} finally {
  httpRequest2.destroy();
}
return Promise.resolve(true)

先按拦截器开发步骤这个,返回点固定的数据。resolve包装数据。
注意跳出逻辑,就是在拦截里做http请求避免循环拦截。

试过了,还是有问题,谢谢大佬,已经提单了

在HarmonyOS Next API 22的@kit.NetworkKit中,unsupported body type异常是由于拦截器处理请求体时,传入的body类型未被识别为支持的类型(如string、ArrayBuffer、FormData等)。排查请求体构造部分,确保数据类型符合NetworkKit的预期格式。

在拦截器的 interceptorHandle 中发起新的 HTTP 请求(httpRequest2.request)并 await,会破坏当前请求的处理流程。框架在拦截器返回后尝试重新组装请求体时,可能由于内部状态被异步操作修改,导致无法识别 body 类型而抛出 unsupported body type。拦截器设计用于修改请求上下文或对标头等做轻量处理,避免在其中创建新的网络请求实例。

回到顶部