# 12.6:HttpClient

HttpClient (opens new window) 是为 OpenHarmony 打造的一个高效的网络请求库,它可以让内容加载更快并节省流量,它以 OkHttp 为基础,整合了 android-async-httpAutobahnAndroidOkGo 等库的功能特性,致力于在 OpenHarmony 打造一款高效易用,功能全面的网络请求库。

# 12.6.1:安装HttpClient

进入项目下的 entry 目录,执行如下命令:

npm config set @ohos:registry=https://repo.harmonyos.com/npm/
npm install @ohos/httpclient --save
1
2

📢:DevEco Studio 的预览器暂时不支持网络请求,只能在模拟器或真机上进行。

# 12.6.2:使用HttpClient

  1. 引入HttpClient模块

    import httpClient from '@ohos/httpclient'
    
    1
  2. 创建HttpClient实例

    import httpClient from '@ohos/httpclient'
    import TimeUnit from '@ohos/httpclient'
    
    let httpClientImpl = new httpClient.HttpClient.Builder()
      .setConnectTimeout(15, TimeUnit.TimeUnit.SECONDS)
      .setReadTimeout(15, TimeUnit.TimeUnit.SECONDS)
      .build();
    
    1
    2
    3
    4
    5
    6
    7

    HttpClient 实例创建完后就可以通过它发起网络请求了。

    📢:一个 HttpClient 实例可以发起多个 http 请求,所以应用内创建一个 HttpClient 实例就可以了。

  3. 发起Get请求

    let request = new httpClient.Request.Builder()
      .url("https://www.baidu.com")                       // 请求地址
      .method("GET")                                      // 请求方式
      .addHeader("Content-Type", "application/json")      // Header设置
      .params("testKey1", "testValue2")                   // 额外参数
      .build();
    
    httpClientImpl.newCall(request).enqueue((result) => {
      console.log("success: " + JSON.stringify(result))   // 成功回调
    }, (error) => {
      console.log("error: " + JSON.stringify(error))      // 失败回调
    })
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
  4. 发起Post请求

    let body = {
      "userName": "OpenHarmony",
      "password": "OpenHarmony666"
    };
    
    let requestBody = httpClient.RequestBody.create(JSON.stringify(body));
    
    let request = new httpClient.Request.Builder()
      .url("https://www.baidu.com")
      .method('POST')
      .body(requestBody)
      .addHeader("Content-Type", "application/json")
      .params("testKey1", "testValue2")
      .build();
    
    httpClientImpl.newCall(request).enqueue((result) => {
      console.log("success: " + JSON.stringify(result))
    }, (error) => {
      console.log("error: " + JSON.stringify(error))
    })
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
  5. 文件下载

    let request = new httpClient.Request.Builder()
      .url("https://www.baidu.com")
      .filePath(localPath)
      .download()
      .build();
    
    httpClientImpl.newCall(request).execute().then((downloadTask) => {
      downloadTask.on('complete', () => {
        console.log("complete");
      });
      downloadTask.on("progress", (err, receivedSize, totalSize) => {
        console.log("progress: " + receivedSize + ", totalSize: " + totalSize);
      });
    }).catch((error) => {
      console.log("error")
    })
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16

    httpClient 的使用很简单,除了这些基本用法外,它还支持请求配置,Cookie 管理,自定义拦截器等,读者可参考官方文档:https://gitee.com/openharmony-tpc/httpclient (opens new window)

# 12.6.3:HttpClient实战

我们通过 Gitee 开放的 API 来请求 OpenHarmony 组件下所有的开源项目,实现:

  1. 在请求阶段弹 Loading 框
  2. 请求成功列举出所有的项目名称

代码如下所示:


import httpClient from '@ohos/httpclient'
import TimeUnit from '@ohos/httpclient'

let httpClientImpl = new httpClient.HttpClient.Builder()
  .setConnectTimeout(15, TimeUnit.TimeUnit.SECONDS)
  .setReadTimeout(15, TimeUnit.TimeUnit.SECONDS)
  .build();

@CustomDialog struct LoadingDialog {

  private controller: CustomDialogController;

  build() {
    Column({space: 10}) {
      LoadingProgress()
        .size({width: 60, height: 60})

      Text("加载中...")
        .fontSize(25)
    }
    .width("60%")
    .padding({top: 10, bottom: 10})
    .backgroundColor(Color.White)
    .borderRadius(10)
  }
}

@Entry @Component struct HttpClientTest {

  controller: CustomDialogController = new CustomDialogController({
    builder: LoadingDialog(),
    cancel: () => {
      console.log("cancel")
    },
    autoCancel: false,
    customStyle: true,
    alignment: DialogAlignment.Center
  });

  @State data: Array<string> = new Array();

  build() {

    Column({space: 10}) {
      Button("读取OpenHarmony开源仓")
        .onClick(() => {
          this.controller.open();
          this.requestData();
        })

      if(this.data.length > 0) {
        List()
      }
    }
    .width('100%')
    .height('100%')
    .padding(10)
  }

  private requestData() {
    let request = new httpClient.Request.Builder()
      .url("https://gitee.com/api/v5/orgs/openharmony/repos")
      .method("GET")
      .addHeader("Content-Type", "application/json")
      .build();

    httpClientImpl.newCall(request).enqueue((result) => {
      console.log("success: " + JSON.stringify(result));
      
      // 数据解析...
      
      this.controller.close();
    }, (error) => {
      console.log("error: " + JSON.stringify(error))
    })
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78

样例运行结果如下图所示:

12_6_3_1

# 12.6.4:小结

本节简单介绍了开源库 HttpClient (opens new window) 的使用,读者可以参考官方指导文档,由于预览器不支持网络请求,笔者条件也有限,身边没有设备验证本节的样例,待笔者有条件后再把该样例补齐,也非常欢迎有条件的读者能帮笔者补齐该样例!

(adsbygoogle = window.adsbygoogle || []).push({});
请作者喝杯咖啡

津公网安备 12011402001367号

津ICP备2020008934号-2

中央网信办互联网违法和不良信息举报中心

天津市互联网违法和不良信息举报中心