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 ? 次閱讀

前言

過了一個(gè)漫長的中秋+國慶假期,大家伙的鴻蒙內(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é)點(diǎn)最后,添加上網(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");//第一個(gè)參數(shù)為協(xié)議,第二個(gè)參數(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ò)訪問是耗時(shí)操作要放線程里面執(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 {

    //獲取這個(gè)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的時(shí)候也帶入了RxJava。 更多retrofit的使用方式,可以參考retrofit在android系統(tǒng)中的實(shí)現(xiàn),鴻蒙系統(tǒng)基本兼容。
編輯:hfy

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

    關(guān)注

    19

    文章

    2946

    瀏覽量

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

    關(guān)注

    183

    文章

    2632

    瀏覽量

    66048
收藏 人收藏

    評論

    相關(guān)推薦

    鴻蒙Flutter實(shí)戰(zhàn):07混合開發(fā)

    。 其優(yōu)點(diǎn)是主項(xiàng)目開發(fā)者可以不關(guān)注Flutter實(shí)現(xiàn),不需要安裝配置Flutter開發(fā)環(huán)境,缺點(diǎn)是無法及時(shí)修改Flutter代碼,也不存在熱重載。 ## 2.基于源碼 通過源碼依賴的當(dāng)時(shí),在原生
    發(fā)表于 10-23 16:00

    HTTP海外訪問優(yōu)化:提升跨國網(wǎng)絡(luò)性能的秘訣

    HTTP海外訪問優(yōu)化是提升跨國網(wǎng)絡(luò)性能的關(guān)鍵,涉及多個(gè)方面的技術(shù)和策略。
    的頭像 發(fā)表于 10-15 08:04 ?171次閱讀

    java反編譯的代碼可以修改么

    的影響。 1. Java反編譯工具 在Java反編譯領(lǐng)域,有一些知名的工具可以幫助開發(fā)者將字節(jié)碼轉(zhuǎn)換回源代碼。這些工具包括: JD-GUI :一個(gè)圖形界
    的頭像 發(fā)表于 09-02 11:00 ?312次閱讀

    鴻蒙開發(fā)就業(yè)前景到底怎么樣?

    門檻與挑戰(zhàn): 鴻蒙開發(fā)需要程序員具備良好的編程語言基礎(chǔ), 并熟悉操作系統(tǒng)原理、分布式系統(tǒng)架構(gòu)、云計(jì)算和人工智能等方面的知識。這種技術(shù)門檻雖然較高,但也為開發(fā)者提供了提升自己技術(shù)水平的機(jī)
    發(fā)表于 05-09 17:37

    【開源鴻蒙】下載OpenHarmony 4.1 Release源代碼

    本文介紹了如何下載開源鴻蒙(OpenHarmony)操作系統(tǒng) 4.1 Release版本的源代碼,該方法同樣可以用于下載OpenHarmony最新開發(fā)版本(master分支)或者4.0 Release、3.2 Release等發(fā)
    的頭像 發(fā)表于 04-27 23:16 ?696次閱讀
    【開源<b class='flag-5'>鴻蒙</b>】下載OpenHarmony 4.1 Release源<b class='flag-5'>代碼</b>

    鴻蒙OS開發(fā)實(shí)例:【HarmonyHttpClient】網(wǎng)絡(luò)框架

    鴻蒙上使用的Http網(wǎng)絡(luò)框架,里面包含純Java實(shí)現(xiàn)的HttpNet,類似okhttp使用,支持同步和異步兩種請求方式;還有鴻蒙版retrofit,和Android版Retrofit相
    的頭像 發(fā)表于 04-12 16:58 ?759次閱讀
    <b class='flag-5'>鴻蒙</b>OS<b class='flag-5'>開發(fā)</b>實(shí)例:【HarmonyHttpClient】<b class='flag-5'>網(wǎng)絡(luò)</b>框架

    鴻蒙開發(fā)實(shí)戰(zhàn):【網(wǎng)絡(luò)管理-Socket連接】

    Socket在網(wǎng)絡(luò)通信方面的應(yīng)用,展示了Socket在兩端設(shè)備的連接驗(yàn)證、聊天通信方面的應(yīng)用。
    的頭像 發(fā)表于 03-19 22:04 ?775次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>開發(fā)</b>實(shí)戰(zhàn):【<b class='flag-5'>網(wǎng)絡(luò)</b>管理-Socket連接】

    鴻蒙實(shí)戰(zhàn)項(xiàng)目開發(fā):【短信服務(wù)】

    Java、前端等等開發(fā)人員,想要轉(zhuǎn)入鴻蒙方向發(fā)展。可以直接領(lǐng)取這份資料輔助你的學(xué)習(xí)。下面是鴻蒙開發(fā)的學(xué)習(xí)路線圖。 ! 高清完整版請前往→[
    發(fā)表于 03-03 21:29

    未來從事鴻蒙開發(fā)?是否會有前景?

    應(yīng)屆畢業(yè)生:有一定Java編程基礎(chǔ),系統(tǒng)學(xué)習(xí)鴻蒙應(yīng)用開發(fā) 想轉(zhuǎn)行/跨行人員:求職、轉(zhuǎn)行,希望趕上時(shí)代風(fēng)口并彎道超車 IT相關(guān)工作者:工作遇上瓶頸,想提升技能,升職加薪 鴻蒙
    發(fā)表于 02-19 21:31

    鴻蒙開發(fā)者預(yù)覽版如何?

    : 高清完整版,可在主頁或qr23.cn/AKFP8k保存。 鴻蒙的趨勢已經(jīng)來到,許多Android、Java、前端的程序員也都聽到風(fēng)口。準(zhǔn)備進(jìn)入到鴻蒙的生態(tài)建設(shè)當(dāng)中。所以2024是最好布局的時(shí)候,趁現(xiàn)在行業(yè)還沒內(nèi)卷。更多詳細(xì)
    發(fā)表于 02-17 21:54

    使用 Taro 開發(fā)鴻蒙原生應(yīng)用 —— 快速上手,鴻蒙應(yīng)用開發(fā)指南

    隨著鴻蒙系統(tǒng)的不斷完善,許多應(yīng)用廠商都希望將自己的應(yīng)用移植到鴻蒙平臺上。最近,Taro 發(fā)布了 v4.0.0-beta.x 版本,支持使用 Taro 快速開發(fā)鴻蒙原生應(yīng)用,也可將現(xiàn)有的
    的頭像 發(fā)表于 02-02 16:09 ?759次閱讀
    使用 Taro <b class='flag-5'>開發(fā)</b><b class='flag-5'>鴻蒙</b>原生應(yīng)用 —— 快速上手,<b class='flag-5'>鴻蒙</b>應(yīng)用<b class='flag-5'>開發(fā)</b>指南

    鴻蒙開發(fā)用什么語言?

    Java的,從API8開始,只能用Arkts,js或著C++開發(fā)了,我們這篇文章重點(diǎn)講下應(yīng)用級別的開發(fā)鴻蒙應(yīng)用開發(fā) 和安卓應(yīng)用和IOS應(yīng)
    的頭像 發(fā)表于 01-30 16:12 ?1381次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>開發(fā)</b>用什么語言?

    java后端能轉(zhuǎn)鴻蒙app開發(fā)

    java后端轉(zhuǎn)鴻蒙app開發(fā)好。 還是前端呢
    發(fā)表于 01-29 18:15

    java redis鎖處理并發(fā)代碼

    問題。 本文將詳細(xì)介紹如何在Java代碼中使用Redis實(shí)現(xiàn)并發(fā)代碼的鎖處理。我們將分為以下幾個(gè)方面來討論: Redis分布式鎖的原理 Redis分布式鎖的實(shí)現(xiàn)方式 在
    的頭像 發(fā)表于 12-04 11:04 ?854次閱讀

    鴻蒙 OS 應(yīng)用開發(fā)初體驗(yàn)

    Package 的縮寫)。是鴻蒙操作系統(tǒng)設(shè)計(jì)的應(yīng)用程序包格式。 .hap 文件包含了應(yīng)用程序的代碼、資源和元數(shù)據(jù)等信息,用于在 HarmonyOS 設(shè)備上安裝和運(yùn)行應(yīng)用程序。 整體開發(fā)流程跟
    發(fā)表于 11-02 19:38