HarmonyOS rcp的interceptor当中获取header总是undefine,而且在拦截器中如何增加header?

HarmonyOS rcp的interceptor当中获取header总是undefine,而且在拦截器中如何增加header?

阅读 499
1 个回答

关于rcp网络组件,自定义拦截器HeaderInterceptor如何给Header赋值

async intercept(context: rcp.RequestContext, next: rcp.RequestHandler): Promise<rcp.Response> {

  context.request.headers!["sign"] = "abab"//
}

参考代码,要用真机测试:

//拦截器接收数据对象
import { rcp } from '@kit.RemoteCommunicationKit';
import { BusinessError } from '@kit.BasicServicesKit';

class ResponseCache {
  private readonly cache: Record<string, rcp.Response> = {};

  getResponse(url: string): rcp.Response {
    return this.cache[url];
  }

  setResponse(url: string, response: rcp.Response): void {
    this.cache[url] = response;
  }
}

//自定义拦截器
class ResponseCachingInterceptor implements rcp.Interceptor {
  private readonly cache: ResponseCache;

  constructor(cache: ResponseCache) {
    this.cache = cache;
  }

  //拦截器获取数据方法定义
  intercept(context: rcp.RequestContext, next: rcp.RequestHandler): Promise<rcp.Response> {
    const url = context.request.url.href;
    const responseFromCache = this.cache.getResponse(url);

    if (responseFromCache) {
      return Promise.resolve(responseFromCache);
    }
    const promise = next.handle(context);
    promise.then((resp) => {
      resp.statusCode;
      resp.headers!["sign"] = "abab"//
      console.log("headers"+JSON.stringify(resp.headers))
      this.cache.setResponse(url, resp);
    });
    return promise;
  }
}
@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  getDataByInterceptor(){
    const cache = new ResponseCache();
    const session = rcp.createSession({
      interceptors: [new ResponseCachingInterceptor(cache)]
    });

    session.get('https://www.index.com').then((response) => {
      console.info('get requestData :'+JSON.stringify(response.request))
      console.info('get headersData :'+JSON.stringify(response.headers))
      console.info('get urlData :'+JSON.stringify(response.effectiveUrl))
      console.info('cache : ' + JSON.stringify(cache))
    }).catch((err: BusinessError) => {
      console.error(`err: err code is ${err.code}, err message is ${err.message}`);
    });
  }

  build() {
    RelativeContainer() {
      Text(this.message)
        .id('HelloWorld')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .onClick(()=>{
          this.getDataByInterceptor()
        })
    }
    .height('100%')
    .width('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏