• 【Harmony OS】【JAVA UI】鸿蒙应用如何集成OKHttp网络三方库


     准备资料


    接口准备

    准备get请求接

    cke_626.png

    Post接口

    cke_1283.png

    参考资料

    1.OKHttp

    2.Android OkHttp常用详解

    如何集成


    1参考OKHttp的方法三

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

    1. allprojects {
    2. repositories {
    3. maven {
    4. url 'https://repo.huaweicloud.com/repository/maven/'
    5. }
    6. maven {
    7. url 'https://developer.huawei.com/repo/'
    8. }
    9. allprojects{
    10. repositories{
    11. mavenCentral()
    12. }
    13. }
    14. }
    15. }

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

    1. implementation '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. "reqPermissions": [
    2. {
    3. "name": "ohos.permission.INTERNET"
    4. }
    5. ],

    注意事项

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

    1. "deviceConfig": {
    2. "default": {
    3. "network": {
    4. "cleartextTraffic": true
    5. }
    6. }
    7. },

    界面实现


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

    1. "1.0" encoding="utf-8"?>
    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. />
    17. <Text
    18. ohos:id="$+id:text_type_Post"
    19. ohos:height="100vp"
    20. ohos:text_alignment="center"
    21. ohos:width="match_parent"
    22. ohos:background_element="#ed6262"
    23. ohos:layout_alignment="horizontal_center"
    24. ohos:text="Post请求"
    25. ohos:text_size="40vp"
    26. />
    27. <Text
    28. ohos:id="$+id:text_result"
    29. ohos:height="match_parent"
    30. ohos:multiple_lines="true"
    31. ohos:text_alignment="center"
    32. ohos:width="match_parent"
    33. ohos:layout_alignment="horizontal_center"
    34. ohos:text="显示结果"
    35. ohos:text_size="40vp"
    36. />
    37. DirectionalLayout>

    cke_16866.png

    Get请求实现


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

    1. TextGet.setClickedListener(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 run() {
    30. textResult.setText(result);
    31. }
    32. });
    33. }
    34. }
    35. });
    36. }
    37. });

    Post请求实现


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

    1. 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 run() {
    34. textResult.setText(result);
    35. }
    36. });
    37. }
    38. }
    39. });
    40. }
    41. });

    运行效果


    具体代码如下

    java 代码

    1. 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. <DirectionalLayout
    2. xmlns:ohos="http://schemas.huawei.com/res/ohos"
    3. ohos:height="match_parent"
    4. ohos:width="match_parent"
    5. ohos:alignment="horizontal_center"
    6. ohos:orientation="vertical">
    7. <Text
    8. ohos:id="$+id:text_type_get"
    9. ohos:height="100vp"
    10. ohos:width="match_parent"
    11. ohos:text_alignment="center"
    12. ohos:layout_alignment="horizontal_center"
    13. ohos:text="Get请求"
    14. ohos:text_size="40vp"
    15. />
    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. />
    26. <Text
    27. ohos:id="$+id:text_result"
    28. ohos:height="match_parent"
    29. ohos:multiple_lines="true"
    30. ohos:text_alignment="center"
    31. ohos:width="match_parent"
    32. ohos:layout_alignment="horizontal_center"
    33. ohos:text="显示结果"
    34. ohos:text_size="40vp"
    35. />
    36. DirectionalLayout>

    运行效果如下

    04e802c1050ff1f71619ef29fbeb1738_384x811.gif%40900-0-90-f.gif

     

     欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh

  • 相关阅读:
    LCD1602液晶显示屏介绍和程序开发
    注意力机制QKV在GAT(Graph Attention Network)的体现
    day02 真正的高并发还得看IO多路复用
    Python之数据库(MYSQL)连接
    有关LED显示屏对比度的知识
    C语言,记负均正
    计算机毕业设计django基于python药房药品管理系统(源码+系统+mysql数据库+Lw文档)
    Dynamic Potential-Based Reward Shaping将势能塑形奖励函数拓展为F(s,t,s‘,t‘)
    nodejs+vue 电子书阅读系统
    粉丝推荐的 GitHub 项目 yyds
  • 原文地址:https://blog.csdn.net/weixin_44708240/article/details/126067220