ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2022-08-08 09:03:32  阅读:468  来源: 互联网

标签:JAVA call void UI Harmony Override new todo public


 准备资料


接口准备

准备get请求接

cke_626.png

Post接口

cke_1283.png

参考资料

1.OKHttp

2.Android OkHttp常用详解

如何集成


1参考OKHttp的方法三

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

allprojects {
    repositories {
        maven {
            url 'https://repo.huaweicloud.com/repository/maven/'
        }
        maven {
            url 'https://developer.huawei.com/repo/'
        }
        allprojects{
            repositories{
                mavenCentral()
            }
        }
    }
}

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

  implementation 'io.openharmony.tpc.thirdlib:okgo:1.0.2'
    implementation 'io.openharmony.tpc.thirdlib:okrx:1.0.2'
    implementation 'io.openharmony.tpc.thirdlib:okrx2:1.0.2'
    implementation 'io.openharmony.tpc.thirdlib:okserver:1.0.2'

在entry的config.json添加 权限 代码如下

 "reqPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }
    ],

注意事项

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

  "deviceConfig": {
    "default": {
      "network": {
        "cleartextTraffic": true
      }
    }
  },

 

界面实现


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

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="horizontal_center"
    ohos:orientation="vertical">

    <Text
        ohos:id="$+id:text_type_get"
        ohos:height="100vp"
        ohos:width="match_parent"
        ohos:text_alignment="center"
        ohos:layout_alignment="horizontal_center"
        ohos:text="Get请求"
        ohos:text_size="40vp"
        />
    <Text
        ohos:id="$+id:text_type_Post"
        ohos:height="100vp"
        ohos:text_alignment="center"
        ohos:width="match_parent"
        ohos:background_element="#ed6262"
        ohos:layout_alignment="horizontal_center"
        ohos:text="Post请求"
        ohos:text_size="40vp"
        />
    <Text
        ohos:id="$+id:text_result"
        ohos:height="match_parent"
        ohos:multiple_lines="true"
        ohos:text_alignment="center"
        ohos:width="match_parent"
        ohos:layout_alignment="horizontal_center"
        ohos:text="显示结果"
        ohos:text_size="40vp"
        />


</DirectionalLayout>

cke_16866.png

 

Get请求实现


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

    TextGet.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                OkHttpClient client = new OkHttpClient();
                Request.Builder requestBuilder = new Request.Builder();
                HttpUrl.Builder urlBuilder=HttpUrl.parse("http://web.juhe.cn/environment/air/cityair").newBuilder();//todo 接口链接
                urlBuilder.addQueryParameter("city","shanghai");//todo  参数
                urlBuilder.addQueryParameter("Key","******");// todo 密钥 key自己申请
                requestBuilder.url(urlBuilder.build());
                Call call = client.newCall(requestBuilder.build());
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //todo 失败回调 需要回到主线程显示结果
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                textResult.setText(e.getMessage());
                            }
                        });

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if(response.isSuccessful()){
                            String result = response.body().string();
                            //todo 处理UI需要切换到UI线程处理
                            getUITaskDispatcher().asyncDispatch(new Runnable() {
                                @Override
                                public void run() {
                                    textResult.setText(result);
                                }
                            });

                        }
                    }
                });
            }
        });

 

Post请求实现


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

TextPost.setClickedListener(new Component.ClickedListener() {
    @Override
    public void onClick(Component component) {
        OkHttpClient client = new OkHttpClient();
        FormBody body = new FormBody.Builder()
                .add("key","*****")// todo 密钥 key自己申请
                .add("date","10/1")//todo 日期参数
                .build();
        Request request = new Request.Builder()
                .url("http://v.juhe.cn/todayOnhistory/queryEvent.php")
                .post(body)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //todo 失败回调 需要回到主线程显示结果
                getUITaskDispatcher().asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        textResult.setText(e.getMessage());
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    String result = response.body().string();
                    //处理UI需要切换到UI线程处理
                    //todo 失败回调 需要回到主线程显示结果
                    getUITaskDispatcher().asyncDispatch(new Runnable() {
                        @Override
                        public void run() {
                            textResult.setText(result);
                        }
                    });
                }
            }
        });
    }
});

 

运行效果


具体代码如下

java 代码

package com.harmony.alliance.myapplication.slice;

import com.harmony.alliance.myapplication.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import okhttp3.*;

import java.io.IOException;

public class MainAbilitySlice extends AbilitySlice {
    Text TextGet,TextPost,textResult;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        TextGet=findComponentById(ResourceTable.Id_text_type_get);
        TextPost=findComponentById(ResourceTable.Id_text_type_Post);
        textResult=findComponentById(ResourceTable.Id_text_result);
        TextGet.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                OkHttpClient client = new OkHttpClient();
                Request.Builder requestBuilder = new Request.Builder();
                HttpUrl.Builder urlBuilder=HttpUrl.parse("http://web.juhe.cn/environment/air/cityair").newBuilder();//todo 接口链接
                urlBuilder.addQueryParameter("city","shanghai");//todo  参数
                urlBuilder.addQueryParameter("Key","6fba58dc50a8e3d92e8a2f63d25c7750");// todo key 密钥
                requestBuilder.url(urlBuilder.build());
                Call call = client.newCall(requestBuilder.build());
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //todo 失败回调 需要回到主线程显示结果
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                textResult.setText(e.getMessage());
                            }
                        });

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if(response.isSuccessful()){
                            String result = response.body().string();
                            //todo 处理UI需要切换到UI线程处理
                            getUITaskDispatcher().asyncDispatch(new Runnable() {
                                @Override
                                public void run() {
                                    textResult.setText(result);
                                }
                            });

                        }
                    }
                });
            }
        });
        TextPost.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                OkHttpClient client = new OkHttpClient();
                FormBody body = new FormBody.Builder()
                        .add("key","7496ca7e5e12c408ef14e465c2bacc79")// todo 密钥
                        .add("date","10/1")//todo 日期参数
                        .build();
                Request request = new Request.Builder()
                        .url("http://v.juhe.cn/todayOnhistory/queryEvent.php")
                        .post(body)
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //todo 失败回调 需要回到主线程显示结果
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                textResult.setText(e.getMessage());
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if(response.isSuccessful()){
                            String result = response.body().string();
                            //处理UI需要切换到UI线程处理
                            //todo 失败回调 需要回到主线程显示结果
                            getUITaskDispatcher().asyncDispatch(new Runnable() {
                                @Override
                                public void run() {
                                    textResult.setText(result);
                                }
                            });
                        }
                    }
                });
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}

 

xml 代码

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="horizontal_center"
    ohos:orientation="vertical">

    <Text
        ohos:id="$+id:text_type_get"
        ohos:height="100vp"
        ohos:width="match_parent"
        ohos:text_alignment="center"
        ohos:layout_alignment="horizontal_center"
        ohos:text="Get请求"
        ohos:text_size="40vp"
        />
    <Text
        ohos:id="$+id:text_type_Post"
        ohos:height="100vp"
        ohos:text_alignment="center"
        ohos:width="match_parent"
        ohos:background_element="#ed6262"
        ohos:layout_alignment="horizontal_center"
        ohos:text="Post请求"
        ohos:text_size="40vp"
        />
    <Text
        ohos:id="$+id:text_result"
        ohos:height="match_parent"
        ohos:multiple_lines="true"
        ohos:text_alignment="center"
        ohos:width="match_parent"
        ohos:layout_alignment="horizontal_center"
        ohos:text="显示结果"
        ohos:text_size="40vp"
        />


</DirectionalLayout>

运行效果如下

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

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

标签:JAVA,call,void,UI,Harmony,Override,new,todo,public
来源: https://www.cnblogs.com/developer-huawei/p/16560545.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有