Hongmeng development actual combat series: One of hongmeng development actual combat series: rounded corners

EventBus/RxBus

preface

After a long mid – Autumn festival + National Day holiday, how are you doing? Don’t like small meng, are spent in eating and drinking, ah, sin sin, sorry those chicken, duck and fish ah, quickly come back to write an article to accept, let us see together, in hongmeng how to send network request.

This article will start with Java native access and then use Retrofit to access the network, which can meet the code needs of most developers for access to the Hong Kong network. You need to do some basic configuration before you start.

Hongmeng system network access basic configuration

1, similar to Android, to access the network, we first need to configure the network access permission, in config.json “module” node at the end of the network access code
"reqPermissions": [{"reason": ""."name": "ohos.permission.INTERNET"}]Copy the code
2. Configure the plaintext access whitelist
"deviceConfig": {
    "default": {
      "network": {
        "usesCleartext": true."securityConfig": {
          "domainSettings": {
            "cleartextPermitted": true."domains": [{"subDomains": true."name": "www.baidu.com"}]}}}}}Copy the code

** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** **

Java native access network

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

HttpDemo.java

package com.example.demo.classone;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;

public class HttpDemo {
    /** * access the url to get the content *@param urlStr
     * @return* /
    public static String httpGet(String urlStr){
        StringBuilder sb = new StringBuilder();
        try{
            // Add HTTPS trust
            SSLContext sslcontext = SSLContext.getInstance("SSL");// The first argument is the protocol, the second argument is the provider (can default)
            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();
        }
        returnsb.toString(); }}Copy the code

HttpX509TrustManager.java

package com.example.demo.classone;
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

Finally, test whether the correct access to the code, note that network access is time-consuming operations to be put in the thread

new Thread(new Runnable() {
        @Override
        public void run(a) {
            String result = HttpDemo.httpGet("http://www.baidu.com");
            HiLog.warn(new HiLogLabel(HiLog.LOG_APP, 0."===demo==="), "Page returns result:"+result);
        }
    }).start();
Copy the code

Use Retrofit to access the web

Add a reference to the Retrofit library in the build.gradle module. I used version 2.5.0 of RetroFIT2 as an example

Implementation 'com. Squareup. Retrofit2: retrofit: 2.5.0' implementation 'com. Squareup. Retrofit2: converter - gson: 2.5.0' Implementation 'IO. Reactivex. Rxjava3: rxjava: 3.0.4'Copy the code

New ApiManager class used to manage access OkHttpClient SSLSocketClient used to provide HTTPS support, ApiResponseConverterFactory is Retrofit converter, will request the results into a String output

ApiManager.java

package com.example.demo.classone;

import com.example.demo.DemoAbilityPackage;
import ohos.app.Environment;
import okhttp3.*;
import retrofit2.Retrofit;

import java.io.File;
import java.util.concurrent.TimeUnit;

/** * provides a way to get Retrofit objects */
public class ApiManager {
    private static final String BUSINESS_BASE_HTTP_URL = "http://www.baidu.com";

    private static Retrofit instance;
    private static OkHttpClient mOkHttpClient;

    private ApiManager(a){}

    public static Retrofit get(a){
        if (instance == null) {synchronized (ApiManager.class){
                if (instance == null){
                    setClient();
                    instance = newRetrofit.Builder().baseUrl(BUSINESS_BASE_HTTP_URL). addConverterFactory(ApiResponseConverterFactory.create()).client(mOkHttpClient).build(); }}}return instance;
    }

    private static void setClient(a){
        if(mOkHttpClient ! =null) {return;
        }
        Cache cache = new Cache(new File(getRootPath(Environment.DIRECTORY_DOCUMENTS),"HttpCache"),1024*1024*100);
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
//.directs (false)// Disables redirects
// .addInterceptor(new AppendUrlParamIntercepter())
                .cache(cache)
                .retryOnConnectionFailure(false)
                .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
                .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                .readTimeout(8,TimeUnit.SECONDS)
                .writeTimeout(8,TimeUnit.SECONDS)
                .connectTimeout(8, TimeUnit.SECONDS);
// .protocols(Collections.singletonList(Protocol.HTTP_1_1));
        mOkHttpClient = builder.build();
        mOkHttpClient.dispatcher().setMaxRequests(100);
    }

    private static String getRootPath(String dirs) {
        String path = DemoAbilityPackage.getInstance().getCacheDir() + "/" + dirs;
        File file = new File(path);
        if(! file.exists()) { file.mkdirs(); }returnpath; }}Copy the code

SSLSocketClient.java

package com.example.demo.classone;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

public class SSLSocketClient {

    // Get this SSLSocketFactory
    public static SSLSocketFactory getSSLSocketFactory(a) {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw newRuntimeException(e); }}/ / get the TrustManager
    private static TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {}@Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {}@Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return newX509Certificate[]{}; }}};return trustAllCerts;
    }


    / / get HostnameVerifier
    public static HostnameVerifier getHostnameVerifier(a) {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true; }};returnhostnameVerifier; }}Copy the code

ApiResponseConverterFactory.java

package com.example.demo.classone;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

/** * BaseResponse converters */
public class ApiResponseConverterFactory extends Converter.Factory {

    public static Converter.Factory create(a){
        return new ApiResponseConverterFactory();
    }

    @Override
    public Converter<ResponseBody, String> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        return new StringResponseBodyConverter();
    }

    @Override
    publicConverter<? , RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {return null;
    }

    class StringResponseBodyConverter implements Converter<ResponseBody.String> {
        @Override
        public String convert(ResponseBody value) throws IOException {
            String s = value.string();
            returns; }}}Copy the code

Start writing business logic using Retrofit

BusinessApiManager.java

package com.example.demo.classone;

/** * Server access interface management */
public class BusinessApiManager {

    private static BusinessApiService instance;
    public static BusinessApiService get(a){
        if (instance == null) {synchronized (BusinessApiManager.class){
                if (instance == null){ instance = ApiManager.get().create(BusinessApiService.class); }}}returninstance; }}Copy the code

BusinessApiService.java

package com.example.demo.classone;

import retrofit2.Call;
import retrofit2.http.*;

/** ** server access interface */
public interface BusinessApiService {
    /** * get the page information *@param url
     * @return* /
    @GET()
    Call<String> getHtmlContent(@Url String url);
}
Copy the code

Test Retrofit to see if it works

BusinessApiManager.get().getHtmlContent("https://www.baidu.com").enqueue(new Callback<String>() {
    @Override
    public void onResponse(Call<String> call, Response<String> response) {
        if(! response.isSuccessful() || response.body() ==null){
            onFailure(null.null);
            return;
        }
        String result = response.body();
        HiLog.warn(new HiLogLabel(HiLog.LOG_APP, 0."===demo==="), "Page returns result:"+result);
    }

    @Override
    public void onFailure(Call<String> call, Throwable throwable) {
        HiLog.warn(new HiLogLabel(HiLog.LOG_APP, 0."===demo==="), "Abnormal page access"); }});Copy the code

conclusion

Hongmeng is based on Java, all Java native apis can be used directly on the Hongmeng system, and any java-related libraries can be directly referenced, such as RxJava when referencing Retrofit. For more information about how to use RetroFIT, you can refer to the implementation of RetroFIT in android system, which is basically compatible with Hongmeng system.

All relevant codes have been uploaded to github: github.com/maolinnan/H…

This is the third article in the series, and there will be more to come. Stay tuned to…… .

If this article inspires you a little bit, I hope you can give it a thumbs-up.