鴻蒙開發實戰系列之一:鴻蒙開發實戰系列之一:圓角java
鴻蒙開發實戰系列之二:鴻蒙開發實戰系列之二:事件總線EventBus/RxBusreact
前言
過了一個漫長的中秋+國慶假期,你們夥的鴻蒙內功修煉的怎麼樣了?難道像小蒙同樣,都在吃吃喝喝中度過麼,哎,罪過罪過,對不起那些雞鴨魚肉啊,趕忙回來寫篇文章收收心,讓咱們一塊兒看看,在鴻蒙中如何發送網絡請求吧。android
本文會從Java原生訪問入手,進而再使用Retrofit訪問網絡,能夠知足絕大部分開發者對於鴻蒙網絡訪問方面的代碼需求,開始以前須要先作一下基礎配置。git
鴻蒙系統網絡訪問基礎配置
一、跟Android相似,要訪問網絡,咱們首先要配置網絡訪問權限,在config.json的"module"節點最後,添加上網絡權限代碼
"reqPermissions": [ { "reason": "", "name": "ohos.permission.INTERNET" } ]
二、配置網絡明文訪問白名單
"deviceConfig": { "default": { "network": { "usesCleartext": true, "securityConfig": { "domainSettings": { "cleartextPermitted": true, "domains": [ { "subDomains": true, "name": "www.baidu.com" } ] } } } } }
其中的name即爲能夠直接http訪問的域名,若是全是https連接則能夠作該不配置,切記域名是不帶http://的,切記域名是不帶http://的,切記域名是不帶http://的,重要的事說三遍。github
Java原生訪問網絡
因爲鴻蒙系統支持Java開發,因此咱們能夠直接使用Java原生的Api來進行網絡訪問 該方式使用了java的url.openConnection() Api來獲取網絡數據json
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 { /** *訪問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(); } }
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; } }
最後是測試是否可以正確訪問的代碼,注意網絡訪問是耗時操做要放線程裏面執行api
new Thread(new Runnable() { @Override public void run() { String result = HttpDemo.httpGet("http://www.baidu.com"); HiLog.warn(new HiLogLabel(HiLog.LOG_APP, 0, "===demo==="), "網頁返回結果:"+result); } }).start();
採用Retrofit訪問網絡
在模塊的build.gradle裏添加Retrofit庫的引用,我這邊採用的是retrofit2的2.5.0版本作示例網絡
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'
新建ApiManager類用來管理獲取OkHttpClient,SSLSocketClient用來提供https支持,ApiResponseConverterFactory是Retrofit的轉換器,將請求結果轉成String輸出session
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; /** * 提供獲取Retrofit對象的方法 */ 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(){} public static Retrofit get(){ if (instance == null){ synchronized (ApiManager.class){ if (instance == null){ setClient(); instance = new Retrofit.Builder().baseUrl(BUSINESS_BASE_HTTP_URL). addConverterFactory(ApiResponseConverterFactory.create()).client(mOkHttpClient).build(); } } } return instance; } private static void setClient(){ if (mOkHttpClient != null){ return; } Cache cache = new Cache(new File(getRootPath(Environment.DIRECTORY_DOCUMENTS),"HttpCache"),1024*1024*100); OkHttpClient.Builder builder = new OkHttpClient.Builder() // .followRedirects(false)//關閉重定向 // .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(); } return path; } }
SSLSocketClient.java
package com.example.demo.classone; import javax.net.ssl.*; import java.security.SecureRandom; import java.security.cert.X509Certificate; public class SSLSocketClient { //獲取這個SSLSocketFactory public static SSLSocketFactory getSSLSocketFactory() { try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, getTrustManager(), new SecureRandom()); return sslContext.getSocketFactory(); } catch (Exception e) { throw new RuntimeException(e); } } //獲取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 new X509Certificate[]{}; } } }; return trustAllCerts; } //獲取HostnameVerifier public static HostnameVerifier getHostnameVerifier() { HostnameVerifier hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }; return hostnameVerifier; } }
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的轉換器 */ public class ApiResponseConverterFactory extends Converter.Factory { public static Converter.Factory create(){ return new ApiResponseConverterFactory(); } @Override public Converter<ResponseBody, String> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { return new StringResponseBodyConverter(); } @Override public Converter<?, 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(); return s; } } }
開始使用Retrofit書寫業務邏輯app
BusinessApiManager.java
package com.example.demo.classone; /** * 服務端訪問接口管理 */ public class BusinessApiManager { private static BusinessApiService instance; public static BusinessApiService get(){ if (instance == null){ synchronized (BusinessApiManager.class){ if (instance == null){ instance = ApiManager.get().create(BusinessApiService.class); } } } return instance; } }
BusinessApiService.java
package com.example.demo.classone; import retrofit2.Call; import retrofit2.http.*; /** * 服務端訪問接口 */ public interface BusinessApiService { /** * 獲取網頁信息 * @param url * @return */ @GET() Call<String> getHtmlContent(@Url String url); }
測試Retrofit是否可以正常使用
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==="), "網頁返回結果:"+result); } @Override public void onFailure(Call<String> call, Throwable throwable) { HiLog.warn(new HiLogLabel(HiLog.LOG_APP, 0, "===demo==="), "網頁訪問異常"); } });
總結
鴻蒙是基於Java開發的,全部Java原生api都是能夠直接在鴻蒙系統上使用的,另外只要和java相關的庫都是能夠直接引用的,例如在引用retrofit的時候也帶入了RxJava。 更多retrofit的使用方式,能夠參考retrofit在android系統中的實現,鴻蒙系統基本兼容。
全部相關代碼已上傳至github:https://github.com/maolinnan/HarmonyosClass
這是本系列的第三篇,後面還會爲你們帶來更多的鴻蒙乾貨,敬請期待......。
若是文章對您有一點啓發的話,但願您能點個贊。