• 鸿蒙应用如何集成OKHttp网络三方库


    准备资料

    接口准备

    准备get请求接

    Post接口

    如何集成

    在项目级别的build.gradle添加如下代码

    1. <pre class="prettyprint hljs nginx" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">allprojects {
    2. repositories {
    3. maven {
    4. url 'https://repo.huaweicloud.com/repository/maven/'
    5. }
    6. maven {
    7. url 'https://developer.huawei.com/repo/'pre>

    在entry的build.gradle添加如下代码

    1. class="prettyprint hljs delphi" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">'io.openharmony.tpc.thirdlib:okgo:1.0.2'
    2. implementation 'io.openharmony.tpc.thirdlib:okrx:1.0.2'
    3. implementation 'io.openharmony.tpc.thirdlib:okrx2:1.0.2'
    4. implementation 'io.openharmony.tpc.thirdlib:okserver:1.0.2'
  • 在entry的config.json添加 ​ 权限 ​ 代码如下

    1. class="prettyprint hljs lua" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">"reqPermissions": [
    2. {
    3. "name": "ohos.permission.INTERNET"

注意事项

如果接口是https的话需要在config.json的deviceConfig里添加如下代码

  1. class="prettyprint hljs lua" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">"deviceConfig": {
  2. "default": {
  3. "network": {
  4. "cleartextTraffic": true

界面实现

在layout的xml中写三个Text标签,第一个Text用于触发get请求的事件,第二个Text用于触发Post请求的事件,第三个Text用于显示结果,代码和效果图如下

  1. <pre class="prettyprint hljs vim" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">
  2. <DirectionalLayout
  3. xmlns:ohos="http://schemas.huawei.com/res/ohos"
  4. ohos:height="match_parent"
  5. ohos:width="match_parent"
  6. ohos:alignment="horizontal_center"
  7. ohos:orientation="vertical">
  8. <Text
  9. ohos:id="$+id:text_type_get"
  10. ohos:height="100vp"
  11. ohos:width="match_parent"
  12. ohos:text_alignment="center"
  13. ohos:layout_alignment="horizontal_center"
  14. ohos:text="Get请求"
  15. ohos:text_size="40vp"
  16. <Text
  17. ohos:id="$+id:text_type_Post"
  18. ohos:height="100vp"
  19. ohos:text_alignment="center"
  20. ohos:width="match_parent"
  21. ohos:background_element="#ed6262"
  22. ohos:layout_alignment="horizontal_center"
  23. ohos:text="Post请求"
  24. ohos:text_size="40vp"
  25. <Text
  26. ohos:id="$+id:text_result"
  27. ohos:height="match_parent"
  28. ohos:multiple_lines="true"
  29. ohos:text_alignment="center"
  30. ohos:width="match_parent"
  31. ohos:layout_alignment="horizontal_center"
  32. ohos:text="显示结果"
  33. ohos:text_size="40vp"
  34. DirectionalLayout>pre>

Get请求实现

在Get的Text点击事件,实现 ​ [Get请求和请求成功之后和请求失败之后(参考 ​ 线程管理开发指导需要将子线程切到Ui线程进行显示数据,代码如下

  1. class="prettyprint hljs java" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">new Component.ClickedListener() {
  2. @Override
  3. public void onClick(Component component) {
  4. OkHttpClient client = new OkHttpClient();
  5. Request.Builder requestBuilder = new Request.Builder();
  6. HttpUrl.Builder urlBuilder=HttpUrl.parse("http://web.juhe.cn/environment/air/cityair").newBuilder();//todo 接口链接
  7. urlBuilder.addQueryParameter("city","shanghai");//todo 参数
  8. urlBuilder.addQueryParameter("Key","******");// todo 密钥 key自己申请
  9. requestBuilder.url(urlBuilder.build());
  10. Call call = client.newCall(requestBuilder.build());
  11. call.enqueue(new Callback() {
  12. @Override
  13. public void onFailure(Call call, IOException e) {
  14. //todo 失败回调 需要回到主线程显示结果
  15. getUITaskDispatcher().asyncDispatch(new Runnable() {
  16. @Override
  17. public void run() {
  18. textResult.setText(e.getMessage());
  19. }
  20. });
  21. }
  22. @Override
  23. public void onResponse(Call call, Response response) throws IOException {
  24. if(response.isSuccessful()){
  25. String result = response.body().string();
  26. //todo 处理UI需要切换到UI线程处理
  27. getUITaskDispatcher().asyncDispatch(new Runnable() {
  28. @Override
  29. public void

Post请求实现

在Post的Text实现点击事件,具体参考​ ​Android OkHttp常用详解​,代码如下

  1. class="prettyprint hljs java" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">TextPost.setClickedListener(new Component.ClickedListener() {
  2. @Override
  3. public void onClick(Component component) {
  4. OkHttpClient client = new OkHttpClient();
  5. FormBody body = new FormBody.Builder()
  6. .add("key","*****")// todo 密钥 key自己申请
  7. .add("date","10/1")//todo 日期参数
  8. .build();
  9. Request request = new Request.Builder()
  10. .url("http://v.juhe.cn/todayOnhistory/queryEvent.php")
  11. .post(body)
  12. .build();
  13. Call call = client.newCall(request);
  14. call.enqueue(new Callback() {
  15. @Override
  16. public void onFailure(Call call, IOException e) {
  17. //todo 失败回调 需要回到主线程显示结果
  18. getUITaskDispatcher().asyncDispatch(new Runnable() {
  19. @Override
  20. public void run() {
  21. textResult.setText(e.getMessage());
  22. }
  23. });
  24. }
  25. @Override
  26. public void onResponse(Call call, Response response) throws IOException {
  27. if(response.isSuccessful()){
  28. String result = response.body().string();
  29. //处理UI需要切换到UI线程处理
  30. //todo 失败回调 需要回到主线程显示结果
  31. getUITaskDispatcher().asyncDispatch(new Runnable() {
  32. @Override
  33. public void

运行效果

具体代码如下

java 代码

  1. class="prettyprint hljs java" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">package com.harmony.alliance.myapplication.slice;
  2. import com.harmony.alliance.myapplication.ResourceTable;
  3. import ohos.aafwk.ability.AbilitySlice;
  4. import ohos.aafwk.content.Intent;
  5. import ohos.agp.components.Component;
  6. import ohos.agp.components.Text;
  7. import okhttp3.*;
  8. import java.io.IOException;
  9. public class MainAbilitySlice extends AbilitySlice
  10. Text TextGet,TextPost,textResult;
  11. @Override
  12. public void onStart(Intent intent) {
  13. super.onStart(intent);
  14. super.setUIContent(ResourceTable.Layout_ability_main);
  15. TextGet=findComponentById(ResourceTable.Id_text_type_get);
  16. TextPost=findComponentById(ResourceTable.Id_text_type_Post);
  17. textResult=findComponentById(ResourceTable.Id_text_result);
  18. TextGet.setClickedListener(new Component.ClickedListener() {
  19. @Override
  20. public void onClick(Component component) {
  21. OkHttpClient client = new OkHttpClient();
  22. Request.Builder requestBuilder = new Request.Builder();
  23. HttpUrl.Builder urlBuilder=HttpUrl.parse("http://web.juhe.cn/environment/air/cityair").newBuilder();//todo 接口链接
  24. urlBuilder.addQueryParameter("city","shanghai");//todo 参数
  25. urlBuilder.addQueryParameter("Key","6fba58dc50a8e3d92e8a2f63d25c7750");// todo key 密钥
  26. requestBuilder.url(urlBuilder.build());
  27. Call call = client.newCall(requestBuilder.build());
  28. call.enqueue(new Callback() {
  29. @Override
  30. public void onFailure(Call call, IOException e) {
  31. //todo 失败回调 需要回到主线程显示结果
  32. getUITaskDispatcher().asyncDispatch(new Runnable() {
  33. @Override
  34. public void run() {
  35. textResult.setText(e.getMessage());
  36. }
  37. });
  38. }
  39. @Override
  40. public void onResponse(Call call, Response response) throws IOException {
  41. if(response.isSuccessful()){
  42. String result = response.body().string();
  43. //todo 处理UI需要切换到UI线程处理
  44. getUITaskDispatcher().asyncDispatch(new Runnable() {
  45. @Override
  46. public void run() {
  47. textResult.setText(result);
  48. }
  49. });
  50. }
  51. }
  52. });
  53. }
  54. });
  55. TextPost.setClickedListener(new Component.ClickedListener() {
  56. @Override
  57. public void onClick(Component component) {
  58. OkHttpClient client = new OkHttpClient();
  59. FormBody body = new FormBody.Builder()
  60. .add("key","7496ca7e5e12c408ef14e465c2bacc79")// todo 密钥
  61. .add("date","10/1")//todo 日期参数
  62. .build();
  63. Request request = new Request.Builder()
  64. .url("http://v.juhe.cn/todayOnhistory/queryEvent.php")
  65. .post(body)
  66. .build();
  67. Call call = client.newCall(request);
  68. call.enqueue(new Callback() {
  69. @Override
  70. public void onFailure(Call call, IOException e) {
  71. //todo 失败回调 需要回到主线程显示结果
  72. getUITaskDispatcher().asyncDispatch(new Runnable() {
  73. @Override
  74. public void run() {
  75. textResult.setText(e.getMessage());
  76. }
  77. });
  78. }
  79. @Override
  80. public void onResponse(Call call, Response response) throws IOException {
  81. if(response.isSuccessful()){
  82. String result = response.body().string();
  83. //处理UI需要切换到UI线程处理
  84. //todo 失败回调 需要回到主线程显示结果
  85. getUITaskDispatcher().asyncDispatch(new Runnable() {
  86. @Override
  87. public void run() {
  88. textResult.setText(result);
  89. }
  90. });
  91. }
  92. }
  93. });
  94. }
  95. });
  96. }
  97. @Override
  98. public void onActive() {
  99. super.onActive();
  100. }
  101. @Override
  102. public void onForeground(Intent intent) {
  103. super.onForeground(intent);
  104. }
  105. }

xml 代码

  1. <pre class="prettyprint hljs vim" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">
  2. <DirectionalLayout
  3. xmlns:ohos="http://schemas.huawei.com/res/ohos"
  4. ohos:height="match_parent"
  5. ohos:width="match_parent"
  6. ohos:alignment="horizontal_center"
  7. ohos:orientation="vertical">
  8. <Text
  9. ohos:id="$+id:text_type_get"
  10. ohos:height="100vp"
  11. ohos:width="match_parent"
  12. ohos:text_alignment="center"
  13. ohos:layout_alignment="horizontal_center"
  14. ohos:text="Get请求"
  15. ohos:text_size="40vp"
  16. <Text
  17. ohos:id="$+id:text_type_Post"
  18. ohos:height="100vp"
  19. ohos:text_alignment="center"
  20. ohos:width="match_parent"
  21. ohos:background_element="#ed6262"
  22. ohos:layout_alignment="horizontal_center"
  23. ohos:text="Post请求"
  24. ohos:text_size="40vp"
  25. <Text
  26. ohos:id="$+id:text_result"
  27. ohos:height="match_parent"
  28. ohos:multiple_lines="true"
  29. ohos:text_alignment="center"
  30. ohos:width="match_parent"
  31. ohos:layout_alignment="horizontal_center"
  32. ohos:text="显示结果"
  33. ohos:text_size="40vp"
  34. DirectionalLayout>pre>

运行效果如下

  • 相关阅读:
    数据结构之位图【原理与实现】
    jupyter notebook 隐藏&显示全部输出内容
    FPGA project : TFT_LCD
    交易履约之结算平台实践 | 京东云技术团队
    make命令常用选项 + gcc 常用选项
    亚马逊,shopee,lazada自养号测评补单操作流程和技巧
    MySQL 高级函数整理
    CTFHUB-信息泄露-目录遍历和PHPINFO
    【网络安全】「漏洞原理」(二)SQL 注入漏洞之理论讲解
    面试中关于 SpringCloud 都需要了解哪些基础?
  • 原文地址:https://blog.csdn.net/weixin_62421895/article/details/126175148