鸿蒙开始起步2

相关文章

鸿蒙起步1

使用OKhttp进行网络请求

step 1 一切的前提配置

	1. 添加权限在src-main-config.json中 module里面添加网络权限
		"reqPermissions": [ { "name": "ohos.permission.INTERNET" }]
	2. deviceConfig中添加可以让http请求
		"deviceConfig": {
	    "default": {
	      "network": { "cleartextTraffic": true}
	    }
  },

step 2 使用okhttp

导入 跟android studio一样 也是在build.gradle里面

	 implementation 'com.squareup.okhttp3:okhttp:3.10.0'
   	 implementation 'com.google.code.gson:gson:2.8.5'//方便解析数据

写一个工具类方便请求,当然也可以直接开整

    public static void startNetWork(String method,String url, HashSet<DataParams> params,RequestBody body,Callback callback) {
        if (method==null){
            return;
        }
        //最多响应十秒
        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).build();
        Request.Builder builder = new Request.Builder();
        HttpUrl.Builder builderUrl = HttpUrl.parse(url).newBuilder();
        builder.url(builderUrl.build());
        if (method.equals("GET")){
            if (params != null) {
                Iterator<DataParams> iterator = params.iterator();
                while (iterator.hasNext()){
                    builderUrl.addQueryParameter(iterator.next().getKey(), iterator.next().getValue());
                }
            }
            builder.method(method,new FormBody.Builder().build());
        }else if (method.equals("POST")){
            builder.post(body);
        }
        Call call = client.newCall(builder.build());
        call.enqueue(callback);
    }

开始请求-处理数据

private void login() {
        String postJson = new Gson().toJson(new UserBean(userName.getText().trim(), passWord.getText().trim()));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), postJson);
        SomeUtils.startNetWork("POST", Comm.Login, null, requestBody, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String getJSON = response.body().string();
                System.out.println(getJSON);
                //想要  Log打印可以往下翻
                mEventHandler mEventHandler = new mEventHandler(EventRunner.create(true));
                try {
                    LoginBean loginBean = new Gson().fromJson(getJSON, LoginBean.class);
                    if (loginBean.isResult()) {
                        //写入本地
                        SomeUtils.setLoginCache(getJSON, LoginAbility.this);
                        //跳转
                        mEventHandler.processEvent(InnerEvent.get(TO_NEXT));
                    } else {
                    	//ToastDialog这东西不能在子线程里面弹出
                        getMainTaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                new ToastDialog(LoginAbility.this)
                                        .setText(loginBean.getMessage())
                                        .show();
                            }
                        });
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

HiLog的打印

	//想要打印日志 需要一个辅助类  HiLogLabel的类型现在只提供了一种 HiLog.LOG_APP
	private static final HiLogLabel LABEL_LOG = new HiLogLabel(HiLog.LOG_APP, 0x00, TAG);
	//真正打印  这里第二个参数是fromat  相当于占位符格式字符串 括号里public为日志可见,private为日志不可见
	HiLog.error(LABEL_LOG, "%{public}s", getJSON);
	

界面跳转

  //类似安卓中的handler
    class mEventHandler extends EventHandler{
        public mEventHandler(EventRunner runner) throws IllegalArgumentException {
            super(runner);
        }

        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            switch (event.eventId){
                case TO_NEXT:
                    Intent intentNext = new Intent();
                    //这里的设计就很难受
                    Operation operation2 = new Intent.OperationBuilder()
                            .withBundleName(MyApplication.PackageName)
                            .withAbilityName(MyApplication.PackageName + ".ability.MainAbility").build();
                    intentNext.setOperation(operation2);
                    startAbility(intentNext);
                    terminateAbility();//相当于finish()
                    break;
            }
        }
    }

鸿蒙的本地轻量级存储

	private static final String ALL_LOCAT_VALUE = "ALL_LOCAT_VALUE";
    private static final String LOGIN_CACHE  = "LOGIN_CACHE";

    public static Preferences getPref(Context context){
        DatabaseHelper helper = new DatabaseHelper(context);
        return helper.getPreferences(ALL_LOCAT_VALUE);
    }

    public static void setLoginCache(String json,Context context){
        Preferences pref = getPref(context);
        pref.putString(LOGIN_CACHE,json);
        pref.flush();
    }

    public static LoginBean.DataDTO getLoginBean(Context context){
        Preferences pref = getPref(context);
        String string = pref.getString(LOGIN_CACHE, "");
        if (string.equals(""))return null;
        LoginBean loginBean = new Gson().fromJson(string, LoginBean.class);
        return loginBean.getData();
    }
  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页

打赏作者

且白

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值