鸿蒙 ark ui 网络请求 我不允许你不会

前言:

最近有在学习这个鸿蒙的ark ui开发 因为鸿蒙不是发布了一个鸿蒙next的测试版本 明年会启动纯血鸿蒙应用 所以我就想提前给大家写一些博客文章

效果图

11-24 16:26:22.005 25156-25156/com.example.httpsrequest E A0ff00/HTTPS: 请求状态 --> 200, %{public}s
11-24 16:26:22.006 25156-25156/com.example.httpsrequest E A0ff00/HTTPS: 请求成功, %{public}s
11-24 16:26:22.006 25156-25156/com.example.httpsrequest E A0ff00/HTTPS: 请求返回数据, "{\"ret\":1,\"data\":[{\"id\":\"8289\",\"title\":\"\\u6cb9\\u7116\\u5927\\u867e\",\"pic\":\"http:\\/\\/www.qubaobei.com\\/ios\\/cf\\/uploadfile\\/132\\/9\\/8289.jpg\",\"collect_num\":\"1670\",\"food_str\":\"\\u5927\\u867e \\u8471 \\u751f\\u59dc \\u690d\\u7269\\u6cb9 \\u6599\\u9152\",\"num\":1670},{\"id\":\"2127\",\"title\":\"\\u56db\\u5ddd\\u56de\\u9505\\u8089\",\"pic\":\"http:\\/\\/www.qubaobei.com\\/ios\\/cf\\/uploadfile\\/132\\/3\\/2127.jpg\",\"collect_num\":\"1592\",\"food_str\":\"\\u732a\\u8089 \\u9752\\u849c \\u9752\\u6912 \\u7ea2\\u6912 \\u59dc\\u7247\",\"num\":1592},{\"id\":\"30630\",\"title\":\"\\u8d85\\u7b80\\u5355\\u8292\\u679c\\u5e03\\u4e01\",\"pic\":\"http:\\/\\/www.qubaobei.com\\/ios\\/cf\\/uploadfile\\/132\\/31\\/30630.jpg\",\"collect_num\":\"1552\",\"food_str\":\"QQ\\u7cd6 \\u725b\\u5976 \\u8292\\u679c\",\"num\":1552},{\"id\":\"9073\",\"title\":\"\\u5bb6\\u5e38\\u7ea2\\u70e7\\u9c7c\",\"pic\":\"http:\\/\\/www.qubaobei.com\\/ios\\/cf\\/uploadfile\\/132\\/10\\/9073.jpg\",\"co

具体实现:

添加网络访问权限 :

在module.json5 里面添加网络访问权限

"requestPermissions": [
  {
    "name": "ohos.permission.INTERNET"
  }
]

创建HTTPS请求

HTTPS协议是位于应用层的一种安全传输协议,与HTTP最大的区别是服务端与客户端之间进行数据传输都会经过TLS/SSL加密。该示例请求测试接口地址,并将请求得到的再日志里面打印出来。效果如图所示:

请求工具类

首先在OkHttpUtil.ets中调用createHttp方法创建一个请求任务,再通过request方法发起网络请求。该方法支持三个参数:url、options以及callback回调,其中options可以设置请求方法、请求头以及超时时间等。



import http from '@ohos.net.http';
import Constants, { ContentType } from '../constant/Constants';
import Logger from './Logger';
import { NewsData } from '../viewmodel/NewsData';


export function httpRequestGet(url: string) {
  return httpRequest(url, http.RequestMethod.GET);
}

export function httpRequestPost(url: string, params?: NewsData) {
  return httpRequest(url, http.RequestMethod.POST, params);
}

function httpRequest(url: string, method: http.RequestMethod,params?: NewsData){
  let httpRequest = http.createHttp();
  let responseResult = httpRequest.request(url, {
    method: method,
    readTimeout: Constants.HTTP_READ_TIMEOUT,//读取超时时间 可选,默认为60000ms
    header: {
      'Content-Type': ContentType.JSON
    },
    connectTimeout: Constants.HTTP_READ_TIMEOUT,//连接超时时间  可选,默认为60000ms
    extraData: params // 请求参数
  });
  return responseResult.then((value: http.HttpResponse)=>{
      Logger.error("请求状态 --> "+value.responseCode)
     if(value.responseCode===200){
       Logger.error("请求成功");
       let getresult = value.result;
       Logger.error('请求返回数据', JSON.stringify(getresult));
       return getresult;
     }
  }).catch((err)=>{
    return "";
  });
}

日志工具类

/*
 * Copyright (c) 2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import hilog from '@ohos.hilog';

class Logger {
  private domain: number;
  private prefix: string;
  private format: string = '%{public}s, %{public}s';

  /**
   * constructor.
   *
   * @param Prefix Identifies the log tag.
   * @param domain Domain Indicates the service domain, which is a hexadecimal integer ranging from 0x0 to 0xFFFFF.
   */
  constructor(prefix: string = 'MyApp', domain: number = 0xFF00) {
    this.prefix = prefix;
    this.domain = domain;
  }

  debug(...args: string[]): void {
    hilog.debug(this.domain, this.prefix, this.format, args);
  }

  info(...args: string[]): void {
    hilog.info(this.domain, this.prefix, this.format, args);
  }

  warn(...args: string[]): void {
    hilog.warn(this.domain, this.prefix, this.format, args);
  }

  error(...args: string[]): void {
    hilog.error(this.domain, this.prefix, this.format, args);
  }
}

export default new Logger('HTTPS', 0xFF00)

然后在view中展示去点击触发请求

import webView from '@ohos.web.webview';
import http from '@ohos.net.http';
import httpGet from '../common/utils/HttpUtil';
import StyleConstant from '../common/constant/StyleConstant';
import CommonConstant from '../common/constant/CommonConstants';
import { httpRequestGet }  from '../common/utils/OKhttpUtil';

@Entry
@Component
struct WebPage {
  controller: webView.WebviewController = new webView.WebviewController();
  @State buttonName: Resource = $r('app.string.request_button_name');
  @State webVisibility: Visibility = Visibility.Hidden;
  @State webSrc: string = CommonConstant.DISH;

  build() {
    Column() {
      Row() {
        Image($r('app.media.ic_network_global'))
          .height($r('app.float.image_height'))
          .width($r('app.float.image_width'))
        TextInput({ placeholder: $r('app.string.input_address'), text: this.webSrc })
          .height($r('app.float.text_input_height'))
          .layoutWeight(1)
          .backgroundColor(Color.White)
          .onChange((value: string) => {
            this.webSrc = value;
          })
      }
      .margin({
        top: $r('app.float.default_margin'),
        left: $r('app.float.default_margin'),
        right: $r('app.float.default_margin')
      })
      .height($r('app.float.default_row_height'))
      .backgroundColor(Color.White)
      .borderRadius($r('app.float.border_radius'))
      .padding({
        left: $r('app.float.default_padding'),
        right: $r('app.float.default_padding')
      })
      Row() {
        Web({ src: this.webSrc, controller: this.controller })
          .zoomAccess(true)
          .height(StyleConstant.FULL_HEIGHT)
          .width(StyleConstant.FULL_WIDTH)
      }
      .visibility(this.webVisibility)
      .height(StyleConstant.WEB_HEIGHT)
      .width(StyleConstant.FULL_WIDTH)
      .align(Alignment.Top)
      Row() {
        Button(this.buttonName)
          .fontSize($r('app.float.button_font_size'))
          .width(StyleConstant.BUTTON_WIDTH)
          .height($r('app.float.button_height'))
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            this.onRequest();

          })
      }
      .height($r('app.float.default_row_height'))
    }
    .width(StyleConstant.FULL_WIDTH)
    .height(StyleConstant.FULL_HEIGHT)
    .backgroundImage($r('app.media.ic_background_image', ImageRepeat.NoRepeat))
    .backgroundImageSize(ImageSize.Cover)
  }

  async onRequest() {
    httpRequestGet(CommonConstant.DISH).then((data)=>{
      console.log("data --- > "+data);
    });

  }
}

分析 模块源码 可知,通过request方法建立请求后,模块底层首先会调用三方库 libcurl 中的curl_easy_init初始化一个简单会话。初始化完成后,接着调用curl_easy_setopt方法设置传输选项。其中CURLOPT_URL用于设置请求的URL地址,对应request中的url参数;CURLOPT_WRITEFUNCTION可以设置一个回调,保存接收的数据;CURLOPT_HEADERDATA支持设置回调,在回调中保存响应头数据。

传输选项设置成功后,调用curl_multi_perform执行传输请求,并通过curl_multi_info_read查询处理句柄是否有消息返回,最后进入HandleCurlData方法处理返回数据。

最后总结

ark ui里面网络请求也比较简单 基本用法我上面的代码有展示了写法基本和前端的js很像 有兴趣的有同学可以深入去研究官网里面提到TLS和SSL 握手过程 我这里就不展开分析了

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容