国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

【HarmonyOS開發(fā)】ArkTs使用Http封裝

這篇具有很好參考價值的文章主要介紹了【HarmonyOS開發(fā)】ArkTs使用Http封裝。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

arkts httputil,HarmonyOS,總結(jié),harmonyos,http,華為

1、鴻蒙中如何進(jìn)行網(wǎng)絡(luò)請求

1.1 三方庫請求

  • @ohos/axios

  • @ohos/retrofit

  • @ohos/httpclient

1.2 鴻蒙原生請求

  • @ohos.net.http

2、ArkTs請求模塊@ohos.net.http

本模塊提供HTTP數(shù)據(jù)請求能力。應(yīng)用可以通過HTTP發(fā)起一個數(shù)據(jù)請求,支持常見的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。

3、@ohos.net.http請求流程

  1. http.createHttp(創(chuàng)建請求實例任務(wù));

  2. request(請求);

  3. destroy(中斷請求);

  4. on(訂閱HTTP Response Header 事件);

  5. off(取消訂閱HTTP Response Header 事件);

  6. once(訂閱HTTP Response Header 事件,但是只觸發(fā)一次);

4、預(yù)覽效果

arkts httputil,HarmonyOS,總結(jié),harmonyos,http,華為

arkts httputil,HarmonyOS,總結(jié),harmonyos,http,華為

5、封裝@ohos.net.http

5.1 函數(shù)式

5.1.1 封裝


import http from '@ohos.net.http';

export interface httpOptions {
  timeOut?: number;
  ContentType?: string;
  header?: Object;
  state?: string;
  callBack?: Function;
}

const HTTP_READ_TIMEOUT = 60000;
const HTTP_CONNECT_TIMEOUT = 60000;
const CONTENT_TYPE = 'application/json'

export function httpRequest(
    url: string,
    method: http.RequestMethod = http.RequestMethod.GET,
    params?: string | Object | ArrayBuffer,
    options?: httpOptions
): Promise<ResponseResult> {
  const request = http.createHttp();
  // 處理狀態(tài)
  if(options?.state) {
    switch (options.state) {
      case 'on':
        request.on('headersReceive', (header) => options.callBack(header));
        break;
      case 'once':
        request.on('headersReceive', (header) => options.callBack(header));
        break;
      case 'off':
        request.off('headersReceive');
        break;
      case 'destroy':
        request.destroy();
        break;
      default:
        break;
    }
    return;
  }

  // 處理請求
  const responseResult = request.request(url, {
    // 超時時間
    readTimeout: options?.timeOut || HTTP_READ_TIMEOUT,
    connectTimeout: options?.timeOut || HTTP_CONNECT_TIMEOUT,
    method,
    extraData: params || {},
    header: options?.header || {
      'Content-Type': options?.ContentType || CONTENT_TYPE
    },
  });
  let serverData: ResponseResult = new ResponseResult();
  // Processes the data and returns.
  return responseResult.then((data: http.HttpResponse) => {
    if (data.responseCode === http.ResponseCode.OK) {
      // Obtains the returned data.
      let result = `${data.result}`;
      let resultJson: ResponseResult = JSON.parse(result);

      serverData.data = resultJson;
      serverData.code = 'success';
      serverData.msg = resultJson?.msg;
    } else {
      serverData.msg = `error info & ${data.responseCode}`;
    }
    return serverData;
  }).catch((err) => {
    serverData.msg = `${err}`;
    return serverData;
  })
}

export class ResponseResult {
  /**
   * Code returned by the network request: success, fail.
   */
  code: string;

  /**
   * Message returned by the network request.
   */
  msg: string | Resource;

  /**
   * Data returned by the network request.
   */
  data: string | Object | ArrayBuffer;

  constructor() {
    this.code = '';
    this.msg = '';
    this.data = '';
  }
}

export default httpRequest;

5.1.2 使用


import httpRequest from '../../utils/requestHttp';

interface resultType {
  resultcode: string;
  reason: string;
  result: resultValType | null;
  error_code: string;
}

interface resultValType {
  city: string;
  realtime: realtimeType;
  future: Object;
}

interface realtimeType {
  temperature: string;
  humidity: string;
  info: string;
  wid: string;
  direct: string;
  power: string;
  aqi: string;
}

@Extend(Text) function textStyle() {
  .fontColor(Color.White)
  .margin({
    left: 12
  })
}

@Entry
@Component
struct httpPages {
  @State html: resultValType = {
    city: '',
    realtime: {
      temperature: '',
      humidity: '',
      info: '',
      wid: '',
      direct: '',
      power: '',
      aqi: '',
    },
    future: undefined
  };
  @State url: string = "http://apis.juhe.cn/simpleWeather/query?key=397c9db4cb0621ad0313123dab416668&city=西安";

  @Styles weatherStyle() {
    .width('100%')
    .padding(6)
    .backgroundColor(Color.Green)
    .borderRadius(8)
  }

  build() {
    Column({space: 10}) {
      Button("請求數(shù)據(jù)")
        .onClick(() => {
          this.httpRequest();
        })
      Column() {
        Text(this.html.city || '--').textStyle().fontWeight(FontWeight.Bold)
      }.weatherStyle().alignItems(HorizontalAlign.Start)
      Column() {
        Text(this.html.realtime.temperature || '--').textStyle()
      }.weatherStyle().alignItems(HorizontalAlign.Start)
      Column() {
        Text(this.html.realtime.humidity || '--').textStyle()
      }.weatherStyle().alignItems(HorizontalAlign.Start)
      Column() {
        Text(this.html.realtime.info || '--').textStyle()
      }.weatherStyle().alignItems(HorizontalAlign.Start)
      Column() {
        Text(this.html.realtime.wid || '--').textStyle()
      }.weatherStyle().alignItems(HorizontalAlign.Start)
      Column() {
        Text(this.html.realtime.direct || '--').textStyle()
      }.weatherStyle().alignItems(HorizontalAlign.Start)
      Column() {
        Text(this.html.realtime.power || '--').textStyle()
      }.weatherStyle().alignItems(HorizontalAlign.Start)
      Column() {
        Text(this.html.realtime.aqi || '--').textStyle()
      }.weatherStyle().alignItems(HorizontalAlign.Start)
    }
    .width('100%')
    .height('100%')
    .padding(10)
  }

  private httpRequest() {
    httpRequest(this.url).then(res => {
      const data: resultType = res.data as resultType;
      this.html = data.result;
      console.info('網(wǎng)絡(luò)結(jié)果:'+JSON.stringify(data));
    });
  }
}

arkts httputil,HarmonyOS,總結(jié),harmonyos,http,華為

5.2?泛型式

5.2.1 封裝

import http from '@ohos.net.http';

// 1、創(chuàng)建RequestOption.ets 配置類
export interface RequestOptions {
  url?: string;
  method?: RequestMethod; // default is GET
  queryParams ?: Record<string, string>;
  extraData?: string | Object | ArrayBuffer;
  header?: Object; // default is 'content-type': 'application/json'
}

export enum RequestMethod {
  OPTIONS = "OPTIONS",
  GET = "GET",
  HEAD = "HEAD",
  POST = "POST",
  PUT = "PUT",
  DELETE = "DELETE",
  TRACE = "TRACE",
  CONNECT = "CONNECT"
}

/**
 * Http請求器
 */
export class HttpCore {
  /**
   * 發(fā)送請求
   * @param requestOption
   * @returns Promise
   */
  request<T>(requestOption: RequestOptions): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      this.sendRequest(requestOption)
        .then((response) => {
          if (typeof response.result !== 'string') {
            reject(new Error('Invalid data type'));

          } else {
            let bean: T = JSON.parse(response.result);
            if (bean) {
              resolve(bean);
            } else {
              reject(new Error('Invalid data type,JSON to T failed'));
            }

          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  private sendRequest(requestOption: RequestOptions): Promise<http.HttpResponse> {
    // 每一個httpRequest對應(yīng)一個HTTP請求任務(wù),不可復(fù)用
    let httpRequest = http.createHttp();

    let resolveFunction, rejectFunction;
    const resultPromise = new Promise<http.HttpResponse>((resolve, reject) => {
      resolveFunction = resolve;
      rejectFunction = reject;
    });

    if (!this.isValidUrl(requestOption.url)) {
      return Promise.reject(new Error('url格式不合法.'));
    }

    let promise = httpRequest.request(this.appendQueryParams(requestOption.url, requestOption.queryParams), {
      method: requestOption.method,
      header: requestOption.header,
      extraData: requestOption.extraData, // 當(dāng)使用POST請求時此字段用于傳遞內(nèi)容
      expectDataType: http.HttpDataType.STRING // 可選,指定返回數(shù)據(jù)的類型
    });

    promise.then((response) => {
      console.info('Result:' + response.result);
      console.info('code:' + response.responseCode);
      console.info('header:' + JSON.stringify(response.header));

      if (http.ResponseCode.OK !== response.responseCode) {
        throw new Error('http responseCode !=200');
      }
      resolveFunction(response);

    }).catch((err) => {
      rejectFunction(err);
    }).finally(() => {
      // 當(dāng)該請求使用完畢時,調(diào)用destroy方法主動銷毀。
      httpRequest.destroy();
    })
    return resultPromise;
  }


  private appendQueryParams(url: string, queryParams: Record<string, string>): string {
    // todo 使用將參數(shù)拼接到url上
    return url;
  }

  private isValidUrl(url: string): boolean {
    //todo 實現(xiàn)URL格式判斷
    return true;
  }
}

// 實例化請求器
const httpCore = new HttpCore();


export class HttpManager {
  private static mInstance: HttpManager;

  // 防止實例化
  private constructor() {
  }

  static getInstance(): HttpManager {
    if (!HttpManager.mInstance) {
      HttpManager.mInstance = new HttpManager();
    }
    return HttpManager.mInstance;
  }

  request<T>(option: RequestOptions): Promise<T> {
    return httpCore.request(option);
  }
}

export default HttpManager;

5.2.2 使用

import httpManager, { RequestMethod } from '../../utils/requestManager';

interface TestBean {
  userId: number,
  id: number,
  title: string,
  completed: boolean
}

private handleClick() {
    httpManager.getInstance()
      .request<TestBean>({
        method: RequestMethod.GET,
        url: 'https://jsonplaceholder.typicode.com/todos/1' //公開的API
      })
      .then((result) => {
        this.text = JSON.stringify(result);
        console.info(JSON.stringify(result));
      })
      .catch((err) => {
        console.error(JSON.stringify(err));
      });
  }

arkts httputil,HarmonyOS,總結(jié),harmonyos,http,華為文章來源地址http://www.zghlxwxcb.cn/news/detail-815627.html

到了這里,關(guān)于【HarmonyOS開發(fā)】ArkTs使用Http封裝的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • HarmonyOS ArkTS HTTP數(shù)據(jù)請求(九)

    HarmonyOS ArkTS HTTP數(shù)據(jù)請求(九)

    日常生活中我們使用應(yīng)用程序看新聞、發(fā)送消息等,都需要連接到互聯(lián)網(wǎng),從服務(wù)端獲取數(shù)據(jù)。例如,新聞應(yīng)用可以從新聞服務(wù)器中獲取最新的熱點新聞,從而給用戶打造更加豐富、更加實用的體驗。 那么要實現(xiàn)這樣一種能實時從服務(wù)端獲取數(shù)據(jù)的場景,就依賴于HTTP數(shù)據(jù)請

    2024年02月03日
    瀏覽(29)
  • 【HarmonyOS北向開發(fā)】-05 ArkTS開發(fā)語言-ArkTS開發(fā)實踐
  • 【HarmonyOS開發(fā)】ArkUI-X 跨平臺框架(使用ArkTs開發(fā)Android&IOS)

    【HarmonyOS開發(fā)】ArkUI-X 跨平臺框架(使用ArkTs開發(fā)Android&IOS)

    ArkUI-X 跨平臺框架進(jìn)一步將 ArkUI 開發(fā)框架擴(kuò)展到了多個OS平臺,目前支持OpenHarmony、HarmonyOS、Android、 iOS,后續(xù)會逐步增加更多平臺支持。開發(fā)者基于一套主代碼,就可以構(gòu)建支持多平臺的精美、高性能應(yīng)用。 React Native 是一個基于 JavaScript 和 React 的開源框架,由 Facebook 開發(fā)和

    2024年01月20日
    瀏覽(27)
  • 【HarmonyOS北向開發(fā)】-04 ArkTS開發(fā)語言-ArkTS基礎(chǔ)知識
  • HarmonyOS(二)—— 初識ArkTS開發(fā)語言(中)之ArkTS的由來和演進(jìn)

    HarmonyOS(二)—— 初識ArkTS開發(fā)語言(中)之ArkTS的由來和演進(jìn)

    在上一篇文章HarmonyOS(二)—— 初識ArkTS開發(fā)語言(上)之TypeScript入門,我初識了TypeScript相關(guān)知識點,也知道ArkTS是華為基于TypeScript發(fā)展演化而來。 從最初的基礎(chǔ)的邏輯交互能力,到具備類型系統(tǒng)的高效工程開發(fā)能力,再到融合聲明式UI、多維狀態(tài)管理等豐富的應(yīng)用開發(fā)能

    2024年02月06日
    瀏覽(32)
  • 零基礎(chǔ)快速上手HarmonyOS ArkTS開發(fā)1---運(yùn)行Hello World、ArkTS開發(fā)語言介紹

    零基礎(chǔ)快速上手HarmonyOS ArkTS開發(fā)1---運(yùn)行Hello World、ArkTS開發(fā)語言介紹

    在華為開發(fā)者大會2023年8月4日(HDC.Together)大會上,HarmonyOS?4正式發(fā)布,其實在2021年那會學(xué)習(xí)了一點鴻蒙的開發(fā): 不過因為現(xiàn)在的鴻蒙手機(jī)完全兼容Android應(yīng)用,所以學(xué)習(xí)動力也不是很足,一直就擱置了,直到今年華為官方出了這么一則消息才讓我對于學(xué)習(xí)它有一種緊迫感了,如

    2024年02月05日
    瀏覽(31)
  • HarmonyOS學(xué)習(xí) -- ArkTS開發(fā)語言入門

    HarmonyOS學(xué)習(xí) -- ArkTS開發(fā)語言入門

    ArkTS是HarmonyOS主力應(yīng)用開發(fā)語言。它在TypeScript(簡稱TS)的基礎(chǔ)上,匹配ArkUI框架,擴(kuò)展了聲明式UI、狀態(tài)管理等相應(yīng)的能力,讓開發(fā)者以更簡潔、更自然的方式開發(fā)跨端應(yīng)用。 JavaScript是一種屬于網(wǎng)絡(luò)的高級腳本語言,已經(jīng)被廣泛應(yīng)用開發(fā),常用來為網(wǎng)頁添加各式各樣的動態(tài)

    2024年02月08日
    瀏覽(27)
  • HarmonyOS開發(fā)(十一):ArkTS組件通用屬性

    用來設(shè)置組件的寬度、邊距 相關(guān)屬性 名稱 參數(shù)說明 描術(shù) width Length 設(shè)置組件的自身寬度,缺省的情況組件寬度為其內(nèi)容的寬度 height Length 設(shè)置組件的自身高度,缺省的情況組件高度為其內(nèi)容的度度 size { ? width?:Length, ? height?:Length } 設(shè)置組件的寬度尺寸 padding Padding | Length 設(shè)

    2024年01月20日
    瀏覽(17)
  • HarmonyOS 自定義抽獎轉(zhuǎn)盤開發(fā)(ArkTS)

    HarmonyOS 自定義抽獎轉(zhuǎn)盤開發(fā)(ArkTS)

    本篇 Codelab 是基于畫布組件、顯式動畫,實現(xiàn)的一個自定義抽獎圓形轉(zhuǎn)盤。包含如下功能: 1.? 通過畫布組件 Canvas,畫出抽獎圓形轉(zhuǎn)盤。 2.? 通過顯式動畫啟動抽獎功能。 3.? 通過自定義彈窗彈出抽中的獎品。 ●?Stack組件:堆疊容器,子組件按照順序依次入棧,后一個子組

    2024年02月07日
    瀏覽(19)
  • HarmonyOS(二)—— 初識ArkTS開發(fā)語言(下)之ArkTS聲明式語法和組件化基礎(chǔ)

    HarmonyOS(二)—— 初識ArkTS開發(fā)語言(下)之ArkTS聲明式語法和組件化基礎(chǔ)

    通過前面ArkTS開發(fā)語言(上)之TypeScript入門以及ArkTS開發(fā)語言(中)之ArkTS的由來和演進(jìn)倆文我們知道了ArkTS的由來以及演進(jìn),知道了ArkTS具備了聲明式語法和組件化特性,今天,搭建一個可刷新的排行榜頁面。在排行榜頁面中,使用循環(huán)渲染控制語法來實現(xiàn)列表數(shù)據(jù)渲染,使

    2024年02月04日
    瀏覽(22)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包