ICode9

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

【HarmonyOS】【JAVA UI】HarmonyOS 网络HttpURLConnection的基本使用

2022-08-04 20:04:50  阅读:258  来源: 互联网

标签:JAVA url HarmonyOS UI httpURLConnection new import todo HttpURLConnection


 参考资料

权限开发指导

线程管理

在鸿蒙(HarmonyOS)环境下,优雅的完成Http访问网络【教程】

api讲解

创建 url

URL url=new URL(urlstr);//todo 创建 url

得到HttpURLConnection对象

HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();

设置请求方式

httpURLConnection.setRequestMethod(“GET”);

建立连接

httpURLConnection.connect()

得到请求状态码

int code=httpURLConnection.getResponseCode()

代码如下

        try {
            String urlstr="https://www.baidu.com/";
            URL url=new URL(urlstr);//todo  创建 url
            //todo 得到HttpURLConnection对象
            HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");//todo 设置请求方式
            httpURLConnection.connect();//todo 建立连接
            int code=httpURLConnection.getResponseCode();//todo 获取请求状态码
            if(code==HttpURLConnection.HTTP_OK){
              //todo  请求成功 处理相关业务
            }else{
            //todo 失败业务处理
            }


        }catch (Exception e){
            e.printStackTrace();
        }

代码运行

config.json添加权限
  "reqPermissions": [{"name":"ohos.permission.INTERNET"}],
设置访问模式
  "deviceConfig": {
    "default": {
      "network": {
        "cleartextTraffic": true
      }
    }
  },

xml布局绘制(在xml 布局设置两个text按钮,一个用text于点击发起网络请求,一个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:orientation="vertical">

    <Text
        ohos:id="$+id:text_helloworld"
        ohos:height="match_content"
        ohos:width="match_parent"
        ohos:text_alignment="center"
        ohos:background_element="#ed6162"
        ohos:layout_alignment="horizontal_center"
        ohos:text="网络请求"
        ohos:text_size="40vp"
        />

    <Text
        ohos:id="$+id:TextResult"
        ohos:height="match_parent"
        ohos:width="match_parent"
        ohos:text_alignment="top|left"
        ohos:text="结果"
        ohos:multiple_lines="true"
        ohos:text_size="20vp"
        />

</DirectionalLayout>

cke_4984.png

java代码实现(分为三个方法 第一个方法实现点击事件 ,第二个方法实现网络请求的事件,第三个方法输入流转化为字符串的功能,最后子线程切换到ui主线程,显示字符串)代码如下

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 ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainAbilitySlice extends AbilitySlice {
    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MY_TAG");
 Text textResult;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        //todo 用于显示结果的按钮
        textResult=findComponentById(ResourceTable.Id_TextResult);
        //todo 实现点击事件
        findComponentById(ResourceTable.Id_text_helloworld).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                //todo 开启线程
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        networkGet();
                    }
                }.start();

            }
        });
    }

    /**
     * 发起网络请求
     */
    public  void  networkGet(){
        try {
            String urlstr="https://www.baidu.com/";
            URL url=new URL(urlstr);//todo  创建 url
            //todo 得到HttpURLConnection对象
            HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");//todo 设置请求方式
            httpURLConnection.connect();//todo 建立连接
            int code=httpURLConnection.getResponseCode();//todo 获取请求状态码
            if(code==HttpURLConnection.HTTP_OK){
                InputStream inputStream=httpURLConnection.getInputStream();//todo 获取网络得到输入流
                byte[] data = read(inputStream);//todo 转化为字节
                String html = new String(data, "UTF-8");// todo 字节转化为字符串
                HiLog.error(LABEL,html);
                //todo 从子线程切换到Ui 主线程
                getUITaskDispatcher().syncDispatch(()   -> {
                    textResult.setText(html);//todo 显示结果
                });
            }


        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 输入流转化为字节
     * @param inStream 输入流
     * @return 返回字节
     * @throws Exception 抛出的异常
     */
    public static byte[] read(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while((len = inStream.read(buffer)) != -1)
        {
            outStream.write(buffer,0,len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

}

运行效果

cke_11821.png

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

标签:JAVA,url,HarmonyOS,UI,httpURLConnection,new,import,todo,HttpURLConnection
来源: https://www.cnblogs.com/developer-huawei/p/16552170.html

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

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

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

ICode9版权所有