日B视频 亚洲,啪啪啪网站一区二区,91色情精品久久,日日噜狠狠色综合久,超碰人妻少妇97在线,999青青视频,亚洲一区二卡,让本一区二区视频,日韩网站推荐

0
  • 聊天消息
  • 系統(tǒng)消息
  • 評論與回復(fù)
登錄后你可以
  • 下載海量資料
  • 學(xué)習(xí)在線課程
  • 觀看技術(shù)視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會員中心
創(chuàng)作中心

完善資料讓更多小伙伴認(rèn)識你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示

基于Java開發(fā)的鴻蒙網(wǎng)絡(luò)訪問方面的代碼

鴻蒙系統(tǒng)HarmonyOS ? 來源:oschina ? 作者:linhy0614 ? 2020-10-16 10:40 ? 次閱讀
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

前言

過了一個漫長的中秋+國慶假期,大家伙的鴻蒙內(nèi)功修煉的怎么樣了?難道像小蒙一樣,都在吃吃喝喝中度過么,哎,罪過罪過,對不起那些雞鴨魚肉啊,趕緊回來寫篇文章收收心,讓我們一起看看,在鴻蒙中如何發(fā)送網(wǎng)絡(luò)請求吧。

本文會從Java原生訪問入手,進(jìn)而再使用Retrofit訪問網(wǎng)絡(luò),可以滿足絕大部分開發(fā)者對于鴻蒙網(wǎng)絡(luò)訪問方面的代碼需求,開始之前需要先做一下基礎(chǔ)配置。

鴻蒙系統(tǒng)網(wǎng)絡(luò)訪問基礎(chǔ)配置

1、跟Android類似,要訪問網(wǎng)絡(luò),我們首先要配置網(wǎng)絡(luò)訪問權(quán)限,在config.json的"module"節(jié)點最后,添加上網(wǎng)絡(luò)權(quán)限代碼

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

2、配置網(wǎng)絡(luò)明文訪問白名單

"deviceConfig": {
    "default": {
      "network": {
        "usesCleartext": true,
        "securityConfig": {
          "domainSettings": {
            "cleartextPermitted": true,
            "domains": [
              {
                "subDomains": true,
                "name": "www.baidu.com"
              }
            ]
          }
        }
      }
    }
  }

其中的name即為可以直接http訪問的域名,如果全是https鏈接則可以做該不配置,切記域名是不帶http://的,切記域名是不帶http://的,切記域名是不帶http://的,重要的事說三遍。

Java原生訪問網(wǎng)絡(luò)

由于鴻蒙系統(tǒng)支持Java開發(fā),所以我們可以直接使用Java原生的Api來進(jìn)行網(wǎng)絡(luò)訪問 該方式使用了java的url.openConnection() Api來獲取網(wǎng)絡(luò)數(shù)據(jù)

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,獲取內(nèi)容
     * @param urlStr
     * @return
     */
    public static String httpGet(String urlStr){
        StringBuilder sb = new StringBuilder();
        try{
            //添加https信任
            SSLContext sslcontext = SSLContext.getInstance("SSL");//第一個參數(shù)為協(xié)議,第二個參數(shù)為提供者(可以缺省)
            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;
    }
}

最后是測試是否能夠正確訪問的代碼,注意網(wǎng)絡(luò)訪問是耗時操作要放線程里面執(zhí)行

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==="), "網(wǎng)頁返回結(jié)果:"+result);
        }
    }).start();

采用Retrofit訪問網(wǎng)絡(luò)

在模塊的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的轉(zhuǎn)換器,將請求結(jié)果轉(zhuǎn)成String輸出

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)//關(guān)閉重定向
//                .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的轉(zhuǎn)換器
 */
public class ApiResponseConverterFactory extends Converter.Factory {

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

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

    @Override
    public Converter requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        return null;
    }

    class StringResponseBodyConverter implements Converter {
        @Override
        public String convert(ResponseBody value) throws IOException {
            String s = value.string();
            return s;
        }
    }
}

開始使用Retrofit書寫業(yè)務(wù)邏輯

BusinessApiManager.java

package com.example.demo.classone;

/**
 * 服務(wù)端訪問接口管理
 */
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.*;

/**
 * 服務(wù)端訪問接口
 */
public interface BusinessApiService {
    /**
     * 獲取網(wǎng)頁信息
     * @param url
     * @return
     */
    @GET()
    Call getHtmlContent(@Url String url);
}

測試Retrofit是否能夠正常使用

BusinessApiManager.get().getHtmlContent("https://www.baidu.com").enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) {
        if (!response.isSuccessful() || response.body() == null){
            onFailure(null,null);
            return;
        }
        String result = response.body();
        HiLog.warn(new HiLogLabel(HiLog.LOG_APP, 0, "===demo==="), "網(wǎng)頁返回結(jié)果:"+result);
    }

    @Override
    public void onFailure(Call call, Throwable throwable) {
        HiLog.warn(new HiLogLabel(HiLog.LOG_APP, 0, "===demo==="), "網(wǎng)頁訪問異常");
    }
});

總結(jié)

鴻蒙是基于Java開發(fā)的,所有Java原生api都是可以直接在鴻蒙系統(tǒng)上使用的,另外只要和java相關(guān)的庫都是可以直接引用的,例如在引用retrofit的時候也帶入了RxJava。 更多retrofit的使用方式,可以參考retrofit在android系統(tǒng)中的實現(xiàn),鴻蒙系統(tǒng)基本兼容。
編輯:hfy

聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場。文章及其配圖僅供工程師學(xué)習(xí)之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問題,請聯(lián)系本站處理。 舉報投訴
  • JAVA
    +關(guān)注

    關(guān)注

    20

    文章

    3012

    瀏覽量

    116874
  • 鴻蒙系統(tǒng)
    +關(guān)注

    關(guān)注

    183

    文章

    2642

    瀏覽量

    70141
收藏 人收藏
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

    評論

    相關(guān)推薦
    熱點推薦

    以龍企招為例,淺談鴻蒙應(yīng)用開發(fā)者激勵計劃 2025 參與心得

    ,也是應(yīng)用合規(guī)運營的基本前提,而我們在開發(fā)時卻忽視了這一關(guān)鍵的風(fēng)控環(huán)節(jié)。 其次是用戶體驗層面的短板,一方面,應(yīng)用僅實現(xiàn)了基礎(chǔ)的招聘功能,交互邏輯簡單,缺乏深度的功能拓展,難以滿足用戶多樣化的求職需求
    發(fā)表于 12-12 10:17

    想體驗鴻蒙生態(tài),該怎么獲取鴻蒙開發(fā)板?有哪些途徑?

    如何快速上手體驗鴻蒙生態(tài)? 想體驗鴻蒙生態(tài),該怎么獲取鴻蒙開發(fā)板?有哪些途徑?
    發(fā)表于 11-29 08:40

    如何申請鴻蒙開發(fā)板?想體驗鴻蒙生態(tài)。

    如何申請鴻蒙開發(fā)板?想體驗鴻蒙生態(tài)。
    發(fā)表于 11-29 08:34

    Java 25正式發(fā)布,重要特性詳解(附代碼示例):靈活構(gòu)造函數(shù)體、模塊導(dǎo)入聲明、AOT方法分析等

    Java 25現(xiàn)已發(fā)布,更多新特性來了!配合Perforce JRebel,代碼修改即時生效,無需重啟服務(wù),即可實現(xiàn)“改完就看效果”。新特性+快工具,讓你的Java開發(fā)體驗雙倍提升!
    的頭像 發(fā)表于 10-29 13:16 ?1726次閱讀
    <b class='flag-5'>Java</b> 25正式發(fā)布,重要特性詳解(附<b class='flag-5'>代碼</b>示例):靈活構(gòu)造函數(shù)體、模塊導(dǎo)入聲明、AOT方法分析等

    知乎開源“智能預(yù)渲染框架” 幾行代碼實現(xiàn)鴻蒙應(yīng)用頁面“秒開”

    ,交互延遲等核心痛點,通過智能預(yù)測用戶瀏覽目標(biāo)進(jìn)行提前渲染,只需幾行代碼即可顯著提升復(fù)雜頁面的加載性能,實現(xiàn)“頁面秒開”的高效體驗,為鴻蒙開發(fā)者帶來
    的頭像 發(fā)表于 08-29 14:32 ?729次閱讀
    知乎開源“智能預(yù)渲染框架” 幾行<b class='flag-5'>代碼</b>實現(xiàn)<b class='flag-5'>鴻蒙</b>應(yīng)用頁面“秒開”

    【匯思博SEEK100開發(fā)板試用體驗】在開發(fā)鴻蒙OS搭建QT開發(fā)環(huán)境

    功能或者網(wǎng)絡(luò)通信失敗等,檢查代碼中對相關(guān)功能的實現(xiàn)邏輯,是否正確調(diào)用了鴻蒙系統(tǒng)提供的 API 以及 Qt 的相關(guān)模塊。例如,在調(diào)用開發(fā)板攝像頭功能時,檢查是否獲取到了正確的攝像頭設(shè)備實
    發(fā)表于 08-24 18:34

    Perforce JRebel 簡介:即時加載代碼變更,加速Java應(yīng)用開發(fā)

    Perforce JRebel 專為Java開發(fā)提速而生!支持跳過構(gòu)建與重新部署,實時加載代碼變更,支持100+框架,無縫集成主流IDE與應(yīng)用服務(wù)器。
    的頭像 發(fā)表于 08-14 14:35 ?1001次閱讀
    Perforce JRebel 簡介:即時加載<b class='flag-5'>代碼</b>變更,加速<b class='flag-5'>Java</b>應(yīng)用<b class='flag-5'>開發(fā)</b>

    【HarmonyOS 5】金融應(yīng)用開發(fā)鴻蒙組件實踐

    【HarmonyOS 5】金融應(yīng)用開發(fā)鴻蒙組件實踐 ##鴻蒙開發(fā)能力 ##HarmonyOS SDK應(yīng)用服務(wù)##鴻蒙金融類應(yīng)用 (金融理財#
    的頭像 發(fā)表于 07-11 18:20 ?1155次閱讀
    【HarmonyOS 5】金融應(yīng)用<b class='flag-5'>開發(fā)</b><b class='flag-5'>鴻蒙</b>組件實踐

    鴻蒙地圖功能開發(fā)【3. 代碼開發(fā)】##地圖開發(fā)##

    ? 在完成了前期準(zhǔn)備工作之后,就可以正式進(jìn)入到代碼開發(fā)的工作中,在官方文檔中,相關(guān)的代碼是很全的,從支持的功能上來看,相比于三方SDK更加全面。 基本項目中包含的地圖展示、marker、路徑規(guī)劃等
    發(fā)表于 06-29 22:59

    鴻蒙地圖功能開發(fā)【1. 開發(fā)準(zhǔn)備】##地圖開發(fā)##

    ? 對于地圖功能的開發(fā),有以下三種思路 使用鴻蒙官方的Map Kit進(jìn)行開發(fā) 使用第三方地圖的SDK(例如高德地圖、百度地圖) 做一個基于h5的地圖頁面,通過Web組件去引入 對于這三種方案,每一種
    發(fā)表于 06-29 22:52

    EtherCAT運動控制卡應(yīng)用開發(fā)教程之Java

    運動控制卡的Java開發(fā)及DLL調(diào)用
    的頭像 發(fā)表于 06-13 14:29 ?1035次閱讀
    EtherCAT運動控制卡應(yīng)用<b class='flag-5'>開發(fā)</b>教程之<b class='flag-5'>Java</b>

    鴻蒙5開發(fā)寶藏案例分享---Web開發(fā)優(yōu)化案例分享

    ),渲染更順滑。 代價: 消耗額外網(wǎng)絡(luò)流量和存儲空間。下多了下錯了就浪費了。 適用場景: 核心頁面的核心、體積較大、加載慢的資源。 代碼示意 (利用資源攔截 + 緩存): **鴻蒙 *
    發(fā)表于 06-12 17:20

    鴻蒙5開發(fā)寶藏案例分享---應(yīng)用并發(fā)設(shè)計

    ?** 鴻蒙并發(fā)編程實戰(zhàn)指南:解鎖ArkTS多線程黑科技** 嘿,開發(fā)者朋友們! 今天給大家扒一扒鴻蒙官方文檔里藏著的并發(fā)編程寶藏—— 100+實戰(zhàn)場景解決方案 !從金融理財?shù)接螒?b class='flag-5'>開發(fā)
    發(fā)表于 06-12 16:19

    使用DevEcoStudio 開發(fā)、編譯鴻蒙 NEXT_APP 以及使用中文插件

    的一站式集成開發(fā)環(huán)境(IDE),專為鴻蒙操作系統(tǒng)(HarmonyOS Next)應(yīng)用和服務(wù)開發(fā)設(shè)計 DevEco Studio,掌握基本操作和開發(fā)流程。 ## 2. 安裝與配置 1
    發(fā)表于 06-11 17:18

    鴻蒙5開發(fā)寶藏案例分享---自由流轉(zhuǎn)的拖拽多屏聯(lián)動

    ? 【干貨預(yù)警】鴻蒙開發(fā)寶藏案例大揭秘!手把手教你玩轉(zhuǎn)常用功能**?** 大家好呀~,今天在扒拉鴻蒙文檔的時候,突然發(fā)現(xiàn)官方竟然藏了一堆超實用的開發(fā)案例! ?** 之前總覺得
    發(fā)表于 06-03 18:50
    讷河市| 壶关县| 图们市| 安塞县| 成都市| 宁明县| 裕民县| 客服| 新营市| 彩票| 周宁县| 北海市| 简阳市| 青川县| 教育| 公主岭市| 郓城县| 乐山市| 双鸭山市| 文水县| 玛沁县| 巴林左旗| 文成县| 昌吉市| 尼玛县| 唐河县| 屏南县| 启东市| 西和县| 巩义市| 虞城县| 蒙山县| 罗定市| 西城区| 绥化市| 富川| 高邮市| 罗甸县| 南澳县| 车致| 海淀区|