HarmonyOS 网络请求示例?

需要网络请求示例,并且包含cookie的持久化。

阅读 416
1 个回答

示例参考:

//下面请求包含了http和rcp两种写法:
import { http } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';

@Entry
@Component
struct HttpDemo {
  private url: string = ''
  private header: Header = new Header();
  private sessionConfig: rcp.SessionConfiguration = {
    cookies: {},
  };

  build() {
    Column({ space: 10 }) {
      Button('session').onClick((event: ClickEvent) => {
        this.request()
      })
      Button('rcpSession').onClick((event: ClickEvent) => {
        this.rcpSession()
      })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.SpaceAround)
  }

  rcpSession() {
    let session = rcp.createSession(this.sessionConfig);
    session.get(this.url).then((response) => {
      // 做完请求校验
      console.log(JSON.stringify(response));
      this.sessionConfig.headers = response.headers
      if (response.cookies && response.cookies?.length > 0) {
        let cookies: rcp.RequestCookies = this.disassemble(response.cookies[0])
        this.sessionConfig.cookies = cookies;
      }
      console.info('header:' + JSON.stringify(this.sessionConfig));
    }).catch((err: BusinessError) => {
      this.sessionConfig.cookies = {}
      console.error("err:" + JSON.stringify(err));
    });
  }

  disassemble(cookie: rcp.ResponseCookie) {
    let coo: Record<string, string> = {}
    if (cookie.value) {
      coo[cookie.name] = cookie.value
    }
    return coo
  }

  request() {
    let httpRequest = http.createHttp();

    httpRequest.request(
      // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
      this.url,
      {
        method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET
        // 开发者根据自身业务需要添加header字段
        header: this.header,
        extraData: 'example'
      }, (err: BusinessError, data: http.HttpResponse) => {
      if (!err) {
        // ...返回值的成功校验

        // 从返回中拿到存放在cookies中的set-cookie值,并将JSESSIONID设置到请求头中,下次请求即可带上sessionId
        console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
        if (data.cookies) {
          let temp: string = data.header['set-cookie'][0]
          let cookies = temp.split(';')
          cookies.forEach(item => {
            if (item.indexOf("JSESSIONID") > -1) {
              this.header.cookie = item
            }
          })
        }
        // 当该请求使用完毕时,调用destroy方法主动销毁
        httpRequest.destroy();
      } else {
        console.error('error:' + JSON.stringify(err));
        // 在请求有问题时清空cookie
        this.header.cookie = ''
        // 取消订阅HTTP响应头事件
        httpRequest.off('headersReceive');
        // 当该请求使用完毕时,调用destroy方法主动销毁
        httpRequest.destroy();
      }
    }
    );
  }
}

class Header {
  public contentType: string = 'text/plain';
  public cookie: string = ''
}
logo
HarmonyOS
子站问答
访问
宣传栏