# Fast-ohos-Networking **Repository Path**: HarmonyOS-tpc/Fast-ohos-Networking ## Basic Information - **Project Name**: Fast-ohos-Networking - **Description**: No description available - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 8 - **Forks**: 2 - **Created**: 2021-04-01 - **Last Updated**: 2025-05-07 ## Categories & Tags **Categories**: harmony, web-dev-toolkits **Tags**: None ## README ## 集成配置 ### 方法一: ``` 按需以module方式导入ohos-networking,jackson-ohos-networking,rx-ohos-networking,rx2-ohos-networking中的一个或者多个module到自己鸿蒙项目中;并使用下面的方式依赖 implementation project(':ohos-networking') implementation project(':jackson-ohos-networking') implementation project(':rx-ohos-networking') implementation project(':rx2-ohos-networking') 另外ohos-networking基础module中必须添加ohos.jar的依赖,否则编译不通过,格式如下所示: api files('D:\\HOSDEMO\\ohosjar\\ohos.jar') 意味着需要把SDK中的ohos.jar复制出来到D盘后,将上述路径更换为你的ohos.jar的实际本地路径 ``` ### 方法二: ``` 编译module生成jar放进libs中 步骤:点击右侧gradle,选择对应的module;比如ohos-networking,然后点击Tasks展开,再点击jar即生成; 生成的jar包在对应的module下面的build\libs中 引入:将生成jar包放入对应entry或者module的libs目录中 ``` ### 方法三 ``` 添加中心仓库 allprojects{ repositories{ mavenCentral() } } 按照需要添加如下依赖配置 implementation 'io.openharmony.tpc.thirdlib:ohos-networking:1.0.2' implementation 'io.openharmony.tpc.thirdlib:jackson-ohos-networking:1.0.2' implementation 'io.openharmony.tpc.thirdlib:rx-ohos-networking:1.0.2' implementation 'io.openharmony.tpc.thirdlib:rx2-ohos-networking:1.0.2' ``` ### jar包使用注意事项 ``` 使用 ohos-networking.jar必须自行依赖okhttp和gson库 使用 jackson-ohos-networking.jar需依赖jackson库 使用 rx-ohos-networking.jar或rx2-ohos-networking.jar需依赖Rxjava1或Rxjava2库 具体三方库版本见entry的依赖配置 ``` ### 在你的项目中使用本库 不要忘记在你的entry的config.json中添加网络权限 ``` "reqPermissions": [ { "name": "ohos.permission.INTERNET" } ] ``` 在你的AbilityPackage中初始化 ``` OhosNetworking.initialize(getApplicationContext()); ``` 配置OkHttpClient ``` // Adding an Network Interceptor for Debugging purpose : OkHttpClient okHttpClient = new OkHttpClient() .newBuilder() .addNetworkInterceptor(new StethoInterceptor()) .build(); OhosNetworking.initialize(getApplicationContext(),okHttpClient); ``` 使用 Jackson Parser ``` 设置 JacksonParserFactory OhosNetworking.setParserFactory(new JacksonParserFactory()); ``` ### 发起一个GET请求 ``` OhosNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}") .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .addHeaders("token", "1234") .setTag("test") .setPriority(Priority.LOW) .build() .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { // do anything with response } @Override public void onError(ANError error) { // handle error } }); ``` ### 发起一个post请求 ``` OhosNetworking.post("https://fierce-cove-29863.herokuapp.com/createAnUser") .addBodyParameter("firstname", "Amit") .addBodyParameter("lastname", "Shekhar") .setTag("test") .setPriority(Priority.MEDIUM) .build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { // do anything with response } @Override public void onError(ANError error) { // handle error } }); ``` 您还可以在POST请求中发布java对象、json、文件等,如 ``` User user = new User(); user.firstname = "Amit"; user.lastname = "Shekhar"; OhosNetworking.post("https://fierce-cove-29863.herokuapp.com/createUser") .addBodyParameter(user) // posting java object .setTag("test") .setPriority(Priority.MEDIUM) .build() .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { // do anything with response } @Override public void onError(ANError error) { // handle error } }); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("firstname", "Amit"); jsonObject.put("lastname", "Shekhar"); } catch (JSONException e) { e.printStackTrace(); } OhosNetworking.post("https://fierce-cove-29863.herokuapp.com/createUser") .addJSONObjectBody(jsonObject) // posting json .setTag("test") .setPriority(Priority.MEDIUM) .build() .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { // do anything with response } @Override public void onError(ANError error) { // handle error } }); OhosNetworking.post("https://fierce-cove-29863.herokuapp.com/postFile") .addFileBody(file) // posting any type of file .setTag("test") .setPriority(Priority.MEDIUM) .build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { // do anything with response } @Override public void onError(ANError error) { // handle error } }); ``` ### 与您自己的JAVA对象一起使用- JSON解析器 ``` /*--------------Example One -> Getting the userList----------------*/ OhosNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}") .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .setTag(this) .setPriority(Priority.LOW) .build() .getAsObjectList(User.class, new ParsedRequestListener>() { @Override public void onResponse(List users) { // do anything with response Log.d(TAG, "userList size : " + users.size()); for (User user : users) { Log.d(TAG, "id : " + user.id); Log.d(TAG, "firstname : " + user.firstname); Log.d(TAG, "lastname : " + user.lastname); } } @Override public void onError(ANError anError) { // handle error } }); /*--------------Example Two -> Getting an user----------------*/ OhosNetworking.get("https://fierce-cove-29863.herokuapp.com/getAnUserDetail/{userId}") .addPathParameter("userId", "1") .setTag(this) .setPriority(Priority.LOW) .build() .getAsObject(User.class, new ParsedRequestListener() { @Override public void onResponse(User user) { // do anything with response Log.d(TAG, "id : " + user.id); Log.d(TAG, "firstname : " + user.firstname); Log.d(TAG, "lastname : " + user.lastname); } @Override public void onError(ANError anError) { // handle error } }); /*-- Note : YourObject.class, getAsObject and getAsObjectList are important here --*/ ``` ### 从服务器下载文件 ``` OhosNetworking.download(url,dirPath,fileName) .setTag("downloadTest") .setPriority(Priority.MEDIUM) .build() .setDownloadProgressListener(new DownloadProgressListener() { @Override public void onProgress(long bytesDownloaded, long totalBytes) { // do anything with progress } }) .startDownload(new DownloadListener() { @Override public void onDownloadComplete() { // do anything after completion } @Override public void onError(ANError error) { // handle error } }); ``` ### 上传文件到服务器 ``` OhosNetworking.upload(url) .addMultipartFile("image",file) .addMultipartParameter("key","value") .setTag("uploadTest") .setPriority(Priority.HIGH) .build() .setUploadProgressListener(new UploadProgressListener() { @Override public void onProgress(long bytesUploaded, long totalBytes) { // do anything with progress } }) .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { // do anything with response } @Override public void onError(ANError error) { // handle error } }); ``` ### 在另一个线程执行器中获得响应和完成(应用程序的主线程中总是返回错误和进度) ``` OhosNetworking.upload(url) .addMultipartFile("image",file) .addMultipartParameter("key","value") .setTag("uploadTest") .setPriority(Priority.HIGH) .build() .setExecutor(Executors.newSingleThreadExecutor()) // setting an executor to get response or completion on that executor thread .setUploadProgressListener(new UploadProgressListener() { @Override public void onProgress(long bytesUploaded, long totalBytes) { // do anything with progress } }) .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { // below code will be executed in the executor provided // do anything with response } @Override public void onError(ANError error) { // handle error } }); ``` ### 设置百分比阈值,如果请求已达到给定阈值,则不取消请求 ``` OhosNetworking.download(url,dirPath,fileName) .setTag("downloadTest") .setPriority(Priority.MEDIUM) .setPercentageThresholdForCancelling(50) // even if at the time of cancelling it will not cancel if 50% .build() // downloading is done.But can be cancalled with forceCancel. .setDownloadProgressListener(new DownloadProgressListener() { @Override public void onProgress(long bytesDownloaded, long totalBytes) { // do anything with progress } }) .startDownload(new DownloadListener() { @Override public void onDownloadComplete() { // do anything after completion } @Override public void onError(ANError error) { // handle error } }); ``` ### 取消一个请求 任何添加标记的请求都能够被取消,像下面一样 ``` OhosNetworking.cancel("tag"); // All the requests with the given tag will be cancelled. OhosNetworking.forceCancel("tag"); // All the requests with the given tag will be cancelled , even if any percent threshold is // set , it will be cancelled forcefully. OhosNetworking.cancelAll(); // All the requests will be cancelled. OhosNetworking.forceCancelAll(); // All the requests will be cancelled , even if any percent threshold is // set , it will be cancelled forcefully. ``` ### 从网络加载一个图片到 ImageView ``` imageView.setDefaultImageResId(R.drawable.default); imageView.setErrorImageResId(R.drawable.error); imageView.setImageUrl(imageUrl); ``` ### 从url获取位图并添加特殊参数 ``` OhosNetworking.get(imageUrl) .setTag("imageRequestTag") .setPriority(Priority.MEDIUM) .setBitmapMaxHeight(100) .setBitmapMaxWidth(100) .setBitmapConfig(Bitmap.Config.ARGB_8888) .build() .getAsBitmap(new BitmapRequestListener() { @Override public void onResponse(Bitmap bitmap) { // do anything with bitmap } @Override public void onError(ANError error) { // handle error } }); ``` ### 错误码处理 ``` public void onError(ANError error) { if (error.getErrorCode() != 0) { // received error from server // error.getErrorCode() - the error code from server // error.getErrorBody() - the error body from server // error.getErrorDetail() - just an error detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); // get parsed error object (If ApiError is your class) ApiError apiError = error.getErrorAsObject(ApiError.class); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } ``` ### 从缓存移除位图并清理缓存 ``` OhosNetworking.evictBitmap(key); // remove a bitmap with key from LruCache OhosNetworking.evictAllBitmap(); // clear LruCache ``` ### Prefetch a request (以便在需要时立即从缓存返回) ``` OhosNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}") .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "30") .setTag(this) .setPriority(Priority.LOW) .build() .prefetch(); ``` ### 为特定请求定制OkHttpClient ``` OkHttpClient okHttpClient = new OkHttpClient().newBuilder() .addInterceptor(new GzipRequestInterceptor()) .build(); OhosNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}") .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .addHeaders("token", "1234") .setTag("test") .setPriority(Priority.LOW) .setOkHttpClient(okHttpClient) // passing a custom okHttpClient .build() .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { // do anything with response } @Override public void onError(ANError error) { // handle error } }); ``` ### 发起有条件请求 (Building a request) ``` ANRequest.GetRequestBuilder getRequestBuilder = new ANRequest.GetRequestBuilder(ApiEndPoint.BASE_URL + ApiEndPoint.CHECK_FOR_HEADER); if(isHeaderRequired){ getRequestBuilder.addHeaders("token", "1234"); } if(executorRequired){ getRequestBuilder.setExecutor(Executors.newSingleThreadExecutor()); } ANRequest anRequest = getRequestBuilder.build(); anRequest.getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { // do anything with response } @Override public void onError(ANError error) { // handle error } }); ``` ### 通过设置AnalyticsListener获取请求的Analytics ``` OhosNetworking.download(url,dirPath,fileName) .setTag("downloadTest") .setPriority(Priority.MEDIUM) .build() .setAnalyticsListener(new AnalyticsListener() { @Override public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }) .setDownloadProgressListener(new DownloadProgressListener() { @Override public void onProgress(long bytesDownloaded, long totalBytes) { // do anything with progress } }) .startDownload(new DownloadListener() { @Override public void onDownloadComplete() { // do anything after completion } @Override public void onError(ANError error) { // handle error } }); Note : If bytesSent or bytesReceived is -1 , it means it is unknown ``` ### 获取响应中的OkHttpResponse ``` OhosNetworking.get("https://fierce-cove-29863.herokuapp.com/getAnUserDetail/{userId}") .addPathParameter("userId", "1") .setTag(this) .setPriority(Priority.LOW) .setUserAgent("getAnUser") .build() .getAsOkHttpResponseAndParsed(new TypeToken() { }, new OkHttpResponseAndParsedRequestListener() { @Override public void onResponse(Response okHttpResponse, User user) { // do anything with okHttpResponse and user } @Override public void onError(ANError anError) { // handle error } }); ``` ### 发起同步请求 ```java ANRequest request = AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}") .addPathParameter("pageNumber", "0") .addQueryParameter("limit", "3") .build(); ANResponse> response = request.executeForObjectList(User.class); if (response.isSuccess()) { List users = responseTwo.getResult(); } else { //handle error } ``` ### 开启日志 ``` OhosNetworking.enableLogging(); // simply enable logging OhosNetworking.enableLogging(LEVEL.HEADERS); // enabling logging with level ``` ### 启用从客户端到服务器的GZIP ``` // Enabling GZIP for Request (Not needed if your server doesn't support GZIP Compression), anyway responses // from server are automatically unGzipped if required. So enable it only if you need your request to be // Gzipped before sending to server(Make sure your server support GZIP Compression). OkHttpClient okHttpClient = new OkHttpClient().newBuilder() .addInterceptor(new GzipRequestInterceptor()) .build(); OhosNetworking.initialize(getApplicationContext(),okHttpClient); ``` ### 重要说明 如果您使用Proguard与Gradle构建系统(通常情况是这样的) ,您不必做任何事情。相应的Proguard规则将自动应用。如果您仍然需要`proguard-rules.pro`中应用的规则,则如下所示: ``` -dontwarn okio.** ``` ### License ``` Copyright (C) 2016 Amit Shekhar Copyright (C) 2011 Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ```