最近在学习鸿蒙开发,在鸿蒙网络请求这块遇到了困难。鸿蒙官网虽然提供了网络请求的API和代码事例,但是描述的过于简单,基本上就是贴代码,所以对于一个初学者来说,仍然看的是一头雾水。Github上也有很多第三方封装的鸿蒙网络请求框架,但是既然是学习就要从最基础的开始,而且那些网络请求框架大致看了下,感觉比较复杂,不太好下手。小编也是花了大概一周的时间,自己慢慢摸索,才入门了鸿蒙的网络请求。下面将小编的一些学习成果分享给大家,帮助大家少走弯路。

一、需要添加网络请求权限

在进行鸿蒙网络请求开发时,先要进行网络请求的权限配置。
配置的地方在config.json文件中,而且针对不同的情况需要的配置还不一样。

1.1 Https的请求地址

现在APP开发默认和推荐的访问地址都是https,鸿蒙也是一样的。如果您在鸿蒙中请求的地址是https的,只需要在config.json文件添加允许网络请求权限的配置:

"reqPermissions": [
      {
        "name": "ohos.permission.GET_NETWORK_INFO"
      },
      {
        "name": "ohos.permission.INTERNET"
      },
      {
        "name": "ohos.permission.SET_NETWORK_INFO"
      }
    ]
1.2 Http的请求地址

如果用的是http的请求,除开添加允许网络请求的权限,还需要配置允许明文信息传输的配置:
鸿蒙官网关于配置的文档

"reqPermissions": [
      {
        "name": "ohos.permission.GET_NETWORK_INFO"
      },
      {
        "name": "ohos.permission.INTERNET"
      },
      {
        "name": "ohos.permission.SET_NETWORK_INFO"
      }
    ]
"deviceConfig": {
    "default": {
      "directLaunch": false,
      "network": {
        "cleartextTraffic": true
      }
    }
  },
二、添加网络请求代码

鸿蒙官网网络请求文档

下面这段代码基本是按照鸿蒙官网提供的网络请求例子来实现的,有少许改动。

public class MainAbilitySlice extends AbilitySlice {

    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MY_TAG");

    private Thread mThread;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        mThread = new Thread(new Runnable() {
            @Override
            public void run() {
                //网络请求需要在子线程中进行
                getRequest();
            }
        });
        mThread.start();
    }

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

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

    private void getRequest() {

        NetManager netManager = NetManager.getInstance(null);
        if (!netManager.hasDefaultNet()) {
            return;
        }
        NetHandle netHandle = netManager.getDefaultNet();

        // 可以获取网络状态的变化
        NetStatusCallback callback = new NetStatusCallback() {
        };
        netManager.addDefaultNetStatusCallback(callback);
        HttpURLConnection connection = null;
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            String urlString = "https://sapi.k780.com";
            URL url = new URL(urlString);
            URLConnection urlConnection = netHandle.openConnection(url, java.net.Proxy.NO_PROXY);
            if (urlConnection instanceof HttpURLConnection) {
                connection = (HttpURLConnection) urlConnection;
            }

            //connection.setRequestMethod("GET");
            connection.setRequestMethod("POST");
            connection.connect();

            try (InputStream inputStream = urlConnection.getInputStream()) {
                byte[] cache = new byte[2 * 1024];
                int len = inputStream.read(cache);
                while (len != -1) {
                    outputStream.write(cache, 0, len);
                    len = inputStream.read(cache);
                }
            } catch (IOException e) {
                HiLog.error(LABEL, "%{public}s", e.getMessage());
            }
            String result = new String(outputStream.toByteArray());
            HiLog.info(LABEL, "%{public}s", result);
        } catch (IOException e) {
            HiLog.error(LABEL, "%{public}s", e.getMessage());
        }
    }
}

输出结果:

00201/MY_TAG: {"success":"0","msgid":"1000501","msg":"请求接口不存在"}

从上面这一大段代码分析,其实主要做了两件事:
(1) 创建HttpURLConnection;
(2) 将请求返回的字节流转成字符串;

所以,我们可以把这两件事情封装一下,写成两个独立的方法。

public class MainAbilitySlice extends AbilitySlice {

    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MY_TAG");

    private Thread mThread;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        mThread = new Thread(new Runnable() {
            @Override
            public void run() {
                getRequest();
            }
        });
        mThread.start();
    }

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

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

    private void getRequest() {

        String requestUrl = "https://sapi.k780.com";
        HttpURLConnection connection = null;
        try {
            connection = getHttpURLConnection(requestUrl,"POST");
            connection.connect();
            String response = getReturnString(connection.getInputStream());
            ZSONObject zsonObject = ZSONObject.stringToZSON(response);
            HiLog.info(LABEL,"%{public}s", zsonObject);

        } catch (Exception e) {
            HiLog.error(LABEL,"%{public}s", e.getMessage());
        }
    }

    private HttpURLConnection getHttpURLConnection(String requestURL, String requestMethod) throws IOException {
        URL url = new URL(requestURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(10*1000);
        connection.setReadTimeout(15*1000);
        connection.setRequestMethod(requestMethod);
        return connection;
    }

    private static String getReturnString(InputStream is) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
            StringBuilder sb = new StringBuilder();
            String line = "";

            while((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            String buf = sb.toString();
            return buf;
        } catch (Exception var5) {
            return null;
        }
    }
}

简单的封装了一下,这样代码结构更加清晰一些。

Demo下载

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐