Preface:

Hello, everyone. I haven’t updated the article for you for some time. I don’t remember exactly how long it will take. The year 2020 has just passed, and I am still learning the development of Hongmeng in the New Year 2021. Recently I looked at the content of the network request part of Hongmeng (this part is mainly in accordance with the development document of Hongmeng mentioned Java UI, JS UI network request please check the official document) so no more nonsense to say that we officially started. Preparations: 1. Install the Hongmeng development environment. You can read my previous article

Initial experience of Huawei Hongmeng System development:

www.jianshu.com/p/f94c847c7…

The effect

The specific implementation

Hongmeng system network access basic configuration

  • Procedure 1 Add the network access permission

Similar to Android, to access the network, we need to configure network access first, add the network access code at the end of the “module” node in config.json

"reqPermissions": [
      {
        "reason": "",
        "name": "ohos.permission.INTERNET"
      }
    ]
Copy the code

  • 2 Set the access mode

If your request URL starts with HTTP, please add the following Settings under deviceConfig in config.json file

deviceConfig": { 
     "default": { 
         "network": { 
             "cleartextTraffic": true 
         } 
     } 
 }, 
Copy the code

Specific code implementation:

  • 1JAVA native request

Because hongmeng system supports Java development, we can directly use Java native Api to access the network. This way uses Java URl.openConnection () Api to obtain network data

Request utility class

We’ve written a utility class based on the HttpURLConnection wrapper to handle our native network requests

package com.example.hms_network.net;
import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
/**
 * 创建人:xuqing
 * 创建时间:2021年1月16日16:11:10
 * 类说明:网络请求工具类
 *
 */
public  class HttpUtils{
    private final static String PARAMETER_SEPARATOR = "&";
    private final static String NAME_VALUE_SEPARATOR = "=";
    /**
     *访问url,获取内容
     * @param urlStr
     * @return
     */
    public static String httpGet(String urlStr){
        StringBuilder sb = new StringBuilder();
        try{
            //添加https信任
            SSLContext sslcontext = SSLContext.getInstance("SSL");//第一个参数为协议,第二个参数为提供者(可以缺省)
            TrustManager[] tm = {new HttpX509TrustManager()};
            sslcontext.init(null, tm, new SecureRandom());
            HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
                public boolean verify(String s, SSLSession sslsession) {
                    System.out.println("WARNING: Hostname is not matched for cert.");
                    return true;
                }
            };
            HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
            HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(10000);
            connection.setConnectTimeout(10000);
            connection.connect();
            int code = connection.getResponseCode();
            if (code == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String temp;
                while ((temp = reader.readLine()) != null) {
                    sb.append(temp);
                }
                reader.close();
            }
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return sb.toString();
    }



    public static String httpGet(String urlStr ,Map<String, String> params){
        StringBuilder sb = new StringBuilder();
        try{
            //添加https信任
            SSLContext sslcontext = SSLContext.getInstance("SSL");//第一个参数为协议,第二个参数为提供者(可以缺省)
            TrustManager[] tm = {new HttpX509TrustManager()};
            sslcontext.init(null, tm, new SecureRandom());
            HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
                public boolean verify(String s, SSLSession sslsession) {
                    System.out.println("WARNING: Hostname is not matched for cert.");
                    return true;
                }
            };
            HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
            HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
            URL url = new URL(getUrl(urlStr,params));
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(10000);
            connection.setConnectTimeout(10000);
            connection.connect();
            int code = connection.getResponseCode();
            if (code == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String temp;
                while ((temp = reader.readLine()) != null) {
                    sb.append(temp);
                }
                reader.close();
            }
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return sb.toString();
    }


    /**
     * get请求,将键值对凭接到url上
     */
    private static  String getUrl(String path, Map<String, String> paramsMap) {
        if(paramsMap != null){
            path = path+"?";
            for (String key: paramsMap.keySet()){
                path = path + key+"="+paramsMap.get(key)+"&";
            }
            path = path.substring(0,path.length()-1);
        }
        return path;
    }



    /**
     * HttpPost 网络请求工具类
     *
     * @param urlStr
     * @return
     */
    public static String httpPost(String urlStr) {

        String result = null;
        URL url = null;
        HttpURLConnection connection = null;
        InputStreamReader in = null;
        try {
            String paramsEncoded = "";
        /*    if (params != null) {
                paramsEncoded = urlParamsFormat(params, "UTF-8");
            }*/
            url = new URL(urlStr);
            if (url.getProtocol().toUpperCase().equals("HTTPS")) {
                trustAllHost();
                HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                connection = https;
            } else {
                connection = (HttpURLConnection) url.openConnection();
            }
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(20000);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Charset", "utf-8");
            DataOutputStream dop = new DataOutputStream(
                    connection.getOutputStream());
         //   dop.writeBytes(paramsEncoded);
            dop.flush();
            dop.close();
            if (connection.getResponseCode() == connection.HTTP_OK) {
                in = new InputStreamReader(connection.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(in);
                StringBuffer strBuffer = new StringBuffer();
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    strBuffer.append(line);
                }
                result = strBuffer.toString();
            } else {
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * HttpPost 网络请求工具类
     *
     * @param urlStr
     * @param params
     * @return
     */
    public static String httpPost(String urlStr, Map<String, String> params) {

        String result = null;
        URL url = null;
        HttpURLConnection connection = null;
        InputStreamReader in = null;
        try {
            String paramsEncoded = "";
            if (params != null) {
                paramsEncoded = urlParamsFormat(params, "UTF-8");
            }
            url = new URL(urlStr);
            if (url.getProtocol().toUpperCase().equals("HTTPS")) {
                trustAllHost();
                HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                connection = https;
            } else {
                connection = (HttpURLConnection) url.openConnection();
            }
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(20000);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Charset", "utf-8");
            DataOutputStream dop = new DataOutputStream(
                    connection.getOutputStream());
            dop.writeBytes(paramsEncoded);
            dop.flush();
            dop.close();
            if (connection.getResponseCode() == connection.HTTP_OK) {
                in = new InputStreamReader(connection.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(in);
                StringBuffer strBuffer = new StringBuffer();
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    strBuffer.append(line);
                }
                result = strBuffer.toString();
            } else {
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * Returns a String that is suitable for use as an application/x-www-form-urlencoded
     * list of parameters in an HTTP PUT or HTTP POST.
     *
     * @param params
     * @param charset
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String urlParamsFormat(Map<String, String> params, String charset) throws UnsupportedEncodingException {
        final StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {
            final String val = params.get(key);
            if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(val)) {
                final String encodedName = URLEncoder.encode(key, charset);
                final String encodedValue = URLEncoder.encode(val, charset);
                if (sb.length() > 0) {
                    sb.append(PARAMETER_SEPARATOR);
                }
                sb.append(encodedName).append(NAME_VALUE_SEPARATOR)
                        .append(encodedValue);
            }
        }

        return sb.toString();
    }

    /**
     * trust all host
     */
    private static void trustAllHost() {
        // Create a trust manager that does not validate certificate chains
        // Android use X509 cert
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[]{};
            }
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
        }};
        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Copy the code

Deal with compatible with the HTTPS code HttpX509TrustManager. Java

package com.example.hms_network.net; import javax.net.ssl.X509TrustManager; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; public class HttpX509TrustManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; }}Copy the code

The native network requests specific invocation tests

    public  void   nativeNet(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String  getjson= HttpUtils.httpGet(url);
                System.out.println("nativeNet   getjson  --- >  "+getjson);
            }
        }).start();
    }
Copy the code

We see on the console that the log outputs the data returned by the request

  • Okhttp request

It is also possible to add the gradle command in build. Gradle and then pull the dependency from the repositorySpecific code

public void okhttpNet() { OkHttpClient client = new OkHttpClient(); final Request request = new Request.Builder() .get() .url(url) .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String responseStr = response.body().string(); System.out.println("responseStr --- > "+responseStr); }}); }Copy the code
  • Okhttputils request

    Build. Gradle can also be used to add gradle commands in build.gradle

   public   void   okhttpUtilsNet(){
        OkHttpUtils.get().
                url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int i) {
                        System.out.println("Exception  --- > "+e);
                    }

                    @Override
                    public void onResponse(String s, int i) {
                        System.out.println("okhttpUtilsNet  s  --- > "+s);
                    }
        });
    }
Copy the code
  • zzrHttp

This is an open source library by ZZR Teacher, and I won’t go into details here. You can go to his tutorial

Tutorial Address:Edu.51cto.com/course/2520…ZZRHTTP is used by adding dependencies in build.gradleThen sing now click pull dependency concrete code demo:

public void zzrHttp(){ ZZRHttp.get(url, new ZZRCallBack.CallBackString() { @Override public void onFailure(int code, String errorMessage) {// HTTP access error, this part works in the main thread, can update UI etc. } @Override public void onResponse(String response) { System.out.println("zzrHttp -- > response " +response); // This part is working in the main thread, can update the UI, etc. }}); }Copy the code

The above is the way I provide you with several hongmeng development of network request, of course, there are other network request libraries based on pure Java language encapsulation theoretically available in Hongmeng above, interested students can know more about me in private because of the space I will not expand on the details.

Conclusion:

Because the Java UI part of hongmeng development uses Java as the basic language, so the API of network request provided by Java can be used directly on Hongmeng as well as including the famous OKHTTP OKHttputils well-known framework can also be perfectly used on Hongmeng. So the whole network part of the request part is relatively simple, of course, these are still more basic and friendly network request use you can according to the actual situation to appropriate packaging processing to better achieve our needs. Finally, I hope my article can help you solve the problem, and I will contribute more useful code to share with you in the future. If you think the article is good, please pay attention and star. Thank you

Project Address:

Yards cloud: gitee.com/qiuyu123/hm…