### Install HarmonyOSNet using OHPM Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Install the HarmonyOSNet library using the ohpm package manager. This command should be executed in the module path where you intend to use the library. ```bash ohpm install @abner/net ``` -------------------------------- ### POST Request Example Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Send data to a server using a POST request. The request is configured to expect a TestModel object in response. ```typescript Net.post("url").request((data) => { //data 为 返回的TestModel对象 }) ``` -------------------------------- ### Calling Dynamic Parameterized Request Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Demonstrates how to call a decorated GET request with dynamic parameters. The `HttpOptions` object is passed during the method invocation. ```typescript private async doHttp(){ const data = await this.getData({ baseUrl: "", //baseUrl header: {}, //头参数 params: {}, //入参 connectTimeout: 1000, //连接超时 readTimeout: 1000, //读取超时 isReturnJson: true,//默认返回json对象 isShowLoading:true//是否显示DialogLoading }) } ``` -------------------------------- ### HTTP Methods Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Supports common HTTP methods like GET, POST, DELETE, PUT, and others like OPTIONS, HEAD, TRACE, CONNECT. ```APIDOC ## GET Request ```typescript @GET("url") getData():Promise | undefined { return undefined } ``` ## POST Request ```typescript @POST("url") getData():Promise | undefined { return undefined } ``` ## DELETE Request ```typescript @DELETE("url") getData():Promise | undefined { return undefined } ``` ## PUT Request ```typescript @PUT("url") private getData():Promise | undefined { return undefined } ``` ## Other Request Methods Supports OPTIONS, HEAD, TRACE, CONNECT by changing the request method. ## Generic NET Decorator ```typescript @NET("url", { method: http.RequestMethod.POST }) getData():Promise | undefined{ return undefined } ``` ``` -------------------------------- ### PUT Request Example Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Update a resource on the server using a PUT request. The method is set up to receive a TestModel object as the response. ```typescript Net.put("url").request((data) => { //data 为 返回的TestModel对象 }) ``` -------------------------------- ### DELETE Request Example Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Initiate a DELETE request to remove a resource from the server. The response is expected to be a TestModel object. ```typescript Net.delete("url").request((data) => { //data 为 返回的TestModel对象 }) ``` -------------------------------- ### GET Request with Decorator Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Standard GET request using the `@GET` decorator. This method returns a Promise that resolves to `TestModel` or undefined. ```typescript @GET("url") getData():Promise | undefined { return undefined } ``` -------------------------------- ### Custom HTTP Method with NET Decorator Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Use the `@NET` decorator to specify custom HTTP methods like POST. This example demonstrates setting the method to POST and returning a JSON string. ```typescript @NET("url", { method: http.RequestMethod.POST }) getData():Promise | undefined{ return undefined } ``` -------------------------------- ### Decorator with DATA Decorator for Parameters Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Use the `@DATA` decorator to pass parameters. Ensure the `@DATA` decorator is placed above the request method decorator (`@GET` in this case). ```typescript @DATA({ baseUrl: "", //baseUrl header: {}, //头参数 params: {}, //入参 connectTimeout: 1000, //连接超时 readTimeout: 1000, //读取超时 isReturnJson: true,//默认返回json对象 isShowLoading:true//是否显示DialogLoading }) @GET("url") getData():Promise | undefined{ return undefined } ``` -------------------------------- ### Global Network Initialization Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Initialize the Net library with global settings such as base URL, timeouts, and error interceptors. This should be done once, typically in AbilityStage. ```typescript Net.getInstance().init({ baseUrl: "https://www.xxx.cn", //设置全局baseurl connectTimeout: 10000, //设置连接超时 readTimeout: 10000, //设置读取超时 netErrorInterceptor: new MyNetErrorInterceptor(), //设置全局错误拦截,需要自行创建,可在这里进行错误处理 header: {}, resultTag: [],//接口返回数据data层参数,比如data,items等等 plugin:[]//插件,类似于拦截器 }) ``` -------------------------------- ### Define and Initialize Custom Global Dialog Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Create a custom dialog builder function and then initialize the Net instance with this custom builder. This allows for a fully customized loading experience across the application. ```typescript //定义全局的Builder @Builder function DialogLoading() { //自己写视图,或者使用自定义组件都行 Column() { Text("我是自定义的Loading") } } //在全局初始化的时候,设置即可 Net.getInstance().init({ loadingDialog: wrapBuilder(DialogLoading) }) ``` -------------------------------- ### Download File with Net API Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Initiates a file download using the Net API. Specify the download URL, context, file path, progress callback, and request completion handler. ```typescript Net.downLoadFile("http://10.47.24.237:8888/harmony/log.har") .setContext(EntryAbility.context) .setFilePath(EntryAbility.filePath) .setProgress((receivedSize, totalSize) => { //监听下载进度 }) .request((data) => { if (data == DownloadTaskState.COMPLETE) { //下载完成 } }) ``` -------------------------------- ### Inject Custom Network Plugin during Initialization Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Inject a custom network plugin during the Net library's initialization by passing an instance of the plugin in the 'plugin' array. ```javascript Net.getInstance().init({ baseUrl: "https://www.xxx.cn", resultTag: ["data", "items"], plugin:[new CustomNetPlugin()] }) ``` -------------------------------- ### Download File Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Initiates a file download process. You can specify the download URL, file path for saving, and progress callbacks. ```APIDOC ## Download File ### Description Downloads a file from a specified URL and saves it to a given path, with options for progress monitoring and task management. ### Method Signature `Net.downLoadFile(url: string)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Methods - `downLoadFile(url: string)`: Sets the download URL. - `setContext(context: Context)`: Sets the application context. - `setFilePath(filePath: string)`: Sets the local path where the downloaded file will be saved. - `setProgress(callback: (receivedSize: number, totalSize: number) => void)`: Registers a callback function to monitor download progress. - `request(callback: (data: DownloadTaskState) => void)`: Initiates the download request. The callback receives the download task state (START, COMPLETE, PAUSE, REMOVE). ### Other Methods - `deleteDownloadTask(callback: (result: boolean) => void)`: Deletes the download task. The callback receives a boolean indicating success or failure. - `suspendDownloadTask(callback: (result: boolean) => void)`: Pauses the download task. The callback receives a boolean indicating success or failure. - `restoreDownloadTask(callback: (result: boolean) => void)`: Resumes a paused download task. The callback receives a boolean indicating success or failure. - `removeProgressCallback()`: Removes the progress callback listener. ### Request Example ```typescript Net.downLoadFile("http://example.com/file.zip") .setContext(EntryAbility.context) .setFilePath("/data/storage/el7/file.zip") .setProgress((receivedSize, totalSize) => { console.log(`Downloaded: ${receivedSize}/${totalSize}`); }) .request((data) => { if (data === DownloadTaskState.COMPLETE) { console.log("Download complete"); } else if (data === DownloadTaskState.ERROR) { console.log("Download error"); } }); ``` ### Response #### Success Response (Download Task State) - `DownloadTaskState.START`: Download has started. - `DownloadTaskState.COMPLETE`: Download has finished successfully. - `DownloadTaskState.PAUSE`: Download has been paused. - `DownloadTaskState.REMOVE`: Download task has been removed or ended. #### Response Example (Callback data for `request` method) ``` -------------------------------- ### Define System Dialog Controller Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Instantiate a CustomDialogController using NetLoadingDialog for a default loading indicator. Set autoCancel to false and customStyle to true for controlled behavior. The dialog is centered by default. ```javascript private mCustomDialogController = new CustomDialogController({ builder: NetLoadingDialog({ loadingText: '请等待...' }), autoCancel: false, customStyle: true, alignment: DialogAlignment.Center }) ``` -------------------------------- ### Upload File with Net API Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Initiates a file upload using the Net API. Configure the upload URL, files, data, progress callback, and request completion handler. ```typescript Net.uploadFile("")//上传的地址 .setUploadFiles([])//上传的文件 [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }] .setUploadData([])//上传的参数 [{ name: "name123", value: "123" }] .setProgress((receivedSize, totalSize) => { //监听上传进度 }) .request((data) => { if (data == UploadTaskState.COMPLETE) { //上传完成 } }) ``` -------------------------------- ### Inject Custom Network Plugin using addNetPlugins Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Add custom network plugins after initialization using the addNetPlugins method. This allows for dynamic addition of interceptors. ```javascript Net.getInstance().addNetPlugins(new CustomNetPlugin()) ``` -------------------------------- ### HTTP Request Methods Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md The Net library supports standard HTTP methods for making requests. ```APIDOC ## HTTP Request Methods The Net library supports standard HTTP methods for making requests. ### GET Request ```typescript Net.get("url").request((data) => { // data is the TestModel object }); ``` ### POST Request ```typescript Net.post("url").request((data) => { // data is the TestModel object }); ``` ### DELETE Request ```typescript Net.delete("url").request((data) => { // data is the TestModel object }); ``` ### PUT Request ```typescript Net.put("url").request((data) => { // data is the TestModel object }); ``` ### Other Request Methods Supports other HTTP methods like OPTIONS, HEAD, TRACE, CONNECT by changing the request method. ```typescript // Example for OPTIONS Net.options("url").request((data) => { // Handle response }); ``` ``` -------------------------------- ### Request Configuration Methods Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Various methods are available to configure request headers, base URLs, parameters, and timeouts. ```APIDOC ## Request Configuration Methods Various methods are available to configure request headers, base URLs, parameters, and timeouts. | Method | Type | Description | |---------------------|-----------------------|--------------------------------------------------| | `setHeaders` | Object | Add custom request headers. | | `setBaseUrl` | string | Override the base URL for the request. | | `setParams` | string / Object / ArrayBuffer | Add parameters, typically for POST requests. | | `setConnectTimeout` | number | Set the connection timeout in milliseconds. | | `setReadTimeout` | number | Set the read timeout in milliseconds. | ``` -------------------------------- ### Request Methods Overview Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md The Net library provides three main methods for asynchronous requests: `request`, `requestString`, and `requestObject`. Choose the method that best suits your data handling needs. ```APIDOC ## Request Methods Overview The Net library provides three main methods for asynchronous requests: `request`, `requestString`, and `requestObject`. Choose the method that best suits your data handling needs. ### `request` Method This method is designed to return specific data objects, such as the `data` field from a JSON response. It can also handle responses where the data is an array. ```typescript // Returning a specific data object Net.get("url").request((data) => { // data is the TestModel object }); // Returning an array of objects Net.get("url").request((data) => { // data is the TestModel[] array }); ``` **Handling Custom Data Field Names:** If your API response uses a field other than `data` (e.g., `items`, `models`), you can configure this globally during initialization or locally using `setResultTag`. ```typescript // Global configuration (recommended) Net.getInstance().init({ resultTag: ["data", "items", "models"] }); // Local configuration Net.get("") .setResultTag(["items"]) .request((data) => { // data is the TestModel object from the 'items' field }); ``` ### `requestString` Method This method simply returns the raw JSON string received from the request. ```typescript Net.get("url").requestString((data) => { // data is the raw JSON string }); ``` ### `requestObject` Method This method returns the entire JSON response object, including fields like `code` and `message`. It's useful when you need the complete response structure. ```typescript // Returning the entire response object (e.g., ApiResult) Net.get("url").requestObject>((data) => { // data is the ApiResult object containing code, message, and data }); ``` ### Callback Functions Requests can include success and optional error callbacks. ```typescript // Success callback only Net.get("url").request((data) => { // Handle successful response }); // Success and error callbacks Net.get("url").request((data) => { // Handle successful response }, (error) => { // Handle error }); ``` ``` -------------------------------- ### Define Custom Network Plugin Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Create a custom network plugin by extending BaseNetPlugin to intercept and modify requests and responses. Implement willSendRequest, didReceive, prepareRequest, and processResult as needed. ```javascript export class CustomNetPlugin extends BaseNetPlugin { //发送Request 请求的所有信息 willSendRequest(request: NetRequest): void { } //收到Response响应,响应的所有信息 didReceive(result: http.HttpResponse): void { } // 请求之前拦截请求 可以做很多操作,比如添加头参,加密等等,如果需要,可重写方法,否则不用,可删除此方法 prepareRequest(request: NetRequest): Promise { return new Promise((resolve: Function) => { resolve(request) }); } //在这里可以修改Response信息,如果需要,可重写此方法,否则不用,可删除此方法 processResult(request: NetRequest, result: http.HttpResponse): Promise { return new Promise((resolve: Function) => { resolve(result) }); } } ``` -------------------------------- ### Upload File Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Initiates a file upload process. You can specify the upload URL, files to upload, additional data, and progress callbacks. ```APIDOC ## Upload File ### Description Uploads files to a specified URL with optional parameters and progress monitoring. ### Method Signature `Net.uploadFile(url: string)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Methods - `uploadFile(url: string)`: Sets the upload URL. - `setUploadFiles(files: Array<{ filename: string, name: string, uri: string, type: string }>)`: Sets the files to be uploaded. - `setUploadData(data: Array<{ name: string, value: string }>)`: Sets additional form data for the upload. - `setProgress(callback: (receivedSize: number, totalSize: number) => void)`: Registers a callback function to monitor upload progress. - `request(callback: (data: UploadTaskState) => void)`: Initiates the upload request. The callback receives the upload task state (START, COMPLETE, ERROR). ### Other Methods - `removeProgressCallback()`: Removes the progress callback listener. - `deleteUploadTask(callback: (result: boolean) => void)`: Deletes the upload task. The callback receives a boolean indicating success or failure. ### Request Example ```typescript Net.uploadFile("upload_url") .setUploadFiles([{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }]) .setUploadData([{ name: "userId", value: "123" }]) .setProgress((receivedSize, totalSize) => { console.log(`Uploaded: ${receivedSize}/${totalSize}`); }) .request((data) => { if (data === UploadTaskState.COMPLETE) { console.log("Upload complete"); } else if (data === UploadTaskState.ERROR) { console.log("Upload error"); } }); ``` ### Response #### Success Response (Upload Task State) - `UploadTaskState.START`: Upload has started. - `UploadTaskState.COMPLETE`: Upload has finished successfully. - `UploadTaskState.ERROR`: An error occurred during upload. #### Response Example (Callback data for `request` method) ``` -------------------------------- ### Add HarmonyOSNet as a Dependency in oh-package.json5 Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Alternatively, add the HarmonyOSNet library as a dependency in your project's oh-package.json5 file. This ensures the library is included in your project's dependencies. ```json "dependencies": { "@abner/net": "^1.1.8" } ``` -------------------------------- ### Other HTTP Request Methods Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Utilize various other HTTP methods like OPTIONS, HEAD, TRACE, and CONNECT by simply changing the request method on the Net object, as provided by the system API. ```typescript // Example for OPTIONS request: // Net.options("url").request(...) ``` -------------------------------- ### POST Request with Decorator Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Standard POST request using the `@POST` decorator. This method returns a Promise that resolves to `TestModel` or undefined. ```typescript @POST("url") getData():Promise | undefined { return undefined } ``` -------------------------------- ### Global Configuration of Result Tag Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Recommended for handling API responses where the data field is not consistently named 'data'. Configure result tags globally during initialization to unify response parsing across different API structures. ```typescript Net.getInstance().init({ resultTag: ["data", "items", "models"]//接口返回数据参数,比如data,items等等 }) ``` -------------------------------- ### Show Global Dialog Loading Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Call this function directly when a network request is made to display a global loading dialog. This assumes the dialog has been configured globally. ```typescript showDialogLoading() ``` -------------------------------- ### Request with Success and Error Callbacks Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Implement comprehensive error handling by providing both success and error callback functions. The success callback is always invoked, while the error callback is executed only when the request fails. ```typescript Net.get("url").request((data) => { //data 为 返回的TestModel对象 }, (error) => { //失败 }) ``` -------------------------------- ### Apache License 2.0 Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md This code snippet contains the full text of the Apache License, Version 2.0, which governs the use of the HarmonyOsNet project. ```text Copyright (C) AbnerMing, HarmonyOsNet 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. ``` -------------------------------- ### Call System Dialog Controller Method Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Use this method to automatically display and hide the dialog managed by the CustomDialogController. This provides a convenient way to show loading states. ```typescript setCustomDialogController(this.mCustomDialogController) ``` -------------------------------- ### Restore Download Task Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Resumes a suspended download task. The callback indicates the success or failure of the operation. ```typescript downLoadRequest.restoreDownloadTask((result) => { if (result) { //成功 } else { //失败 } }) ``` -------------------------------- ### Return JSON String with Decorator Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Use the `isReturnJson: true` option to specify that the response should be a JSON string. This method returns a Promise that resolves to a string or undefined. ```typescript @GET("url",{isReturnJson: true}) getData():Promise | undefined { return undefined } ``` -------------------------------- ### Decorator with Dynamic Parameter Passing Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Pass dynamic parameters to the decorated method. The `HttpOptions` object can be passed as an argument to handle variable parameters like pagination. ```typescript @GET("url") getData(data? : HttpOptions):Promise | undefined { return undefined } ``` -------------------------------- ### Request Return Types Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Decorators can return either a JSON string or a JSON object. The default is a JSON object. ```APIDOC ## Returning JSON String ```typescript @GET("url", {isReturnJson: true}) getData():Promise | undefined { return undefined } ``` ## Returning JSON Object (Default) ```typescript @GET("url") getData():Promise | undefined { return undefined } ``` ``` -------------------------------- ### Request Object with Base Class Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md To avoid repeating common fields like 'code' and 'message' in response objects, define a base class (e.g., ApiResult) and use it with requestObject for cleaner type definitions. ```typescript export class ApiResult { code: number message: string data: T } Net.get("url").requestObject>((data) => { //data 为 返回的ApiResult对象 }) ``` -------------------------------- ### PUT Request with Decorator Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Standard PUT request using the `@PUT` decorator. This method returns a Promise that resolves to `TestModel` or undefined. ```typescript @PUT("url") private getData():Promise | undefined { return undefined } ``` -------------------------------- ### Suspend Download Task Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Pauses an active download task. The callback confirms if the suspension was successful. ```typescript downLoadRequest.suspendDownloadTask((result) => { if (result) { //暂停成功 } else { //暂停失败 } }) ``` -------------------------------- ### Request with Success Callback Only Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Handle only the successful API response using a single callback function. This is suitable when error handling is managed elsewhere or is not critical for this specific request. ```typescript Net.get("url").request((data) => { //data 为 返回的TestModel对象 }) ``` -------------------------------- ### Decorator with Static Parameter Passing Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Pass static parameters directly within the decorator configuration. This includes options like `baseUrl`, `header`, `params`, timeouts, and response type. ```typescript @GET("url", { baseUrl: "", //baseUrl header: {}, //头参数 params: {}, //入参 connectTimeout: 1000, //连接超时 readTimeout: 1000, //读取超时 isReturnJson: true,//默认返回json对象 isShowLoading:true//是否显示DialogLoading }) private getData():Promise | undefined { return undefined } ``` -------------------------------- ### Request String Method Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Use the requestString method to retrieve the raw JSON string response from the API. This is useful when you need to process the response as a string before parsing. ```typescript Net.get("url").requestString((data) => { //data 为 返回的json字符串 }) ``` -------------------------------- ### Return JSON Object with Decorator Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md By default, the decorator returns a JSON object. Specify the expected model type in the Promise. This method returns a Promise that resolves to `TestModel` or undefined. ```typescript @GET("url") getData():Promise | undefined { return undefined } ``` -------------------------------- ### Decorator Parameter Passing Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Parameters can be passed directly in the decorator or dynamically during invocation. The `@DATA` decorator must be placed above the request method decorator. ```APIDOC ## Direct Parameter Passing ```typescript @GET("url", { baseUrl: "", //baseUrl header: {}, params: {}, connectTimeout: 1000, //连接超时 readTimeout: 1000, //读取超时 isReturnJson: true,//默认返回json对象 isShowLoading:true//是否显示DialogLoading }) private getData():Promise | undefined { return undefined } ``` ## Dynamic Parameter Passing ```typescript @GET("url") getData(data? : HttpOptions):Promise | undefined { return undefined } ``` ### Invocation Example ```typescript private async doHttp(){ const data = await this.getData({ baseUrl: "", //baseUrl header: {}, params: {}, connectTimeout: 1000, //连接超时 readTimeout: 1000, //读取超时 isReturnJson: true,//默认返回json对象 isShowLoading:true//是否显示DialogLoading }) } ``` ## Using @DATA Decorator ```typescript @DATA({ baseUrl: "", //baseUrl header: {}, params: {}, connectTimeout: 1000, //连接超时 readTimeout: 1000, //读取超时 isReturnJson: true,//默认返回json对象 isShowLoading:true//是否显示DialogLoading }) @GET("url") getData():Promise | undefined{ return undefined } ``` ``` -------------------------------- ### DELETE Request with Decorator Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Standard DELETE request using the `@DELETE` decorator. This method returns a Promise that resolves to `TestModel` or undefined. ```typescript @DELETE("url") getData():Promise | undefined { return undefined } ``` -------------------------------- ### Remove Download Task Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Removes a download task. The callback indicates whether the removal was successful. ```typescript downLoadRequest.deleteDownloadTask((result) => { if (result) { //移除成功 } else { //移除失败 } }) ``` -------------------------------- ### Remove Download Progress Callback Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Removes the progress listener from a download task. ```typescript downLoadRequest.removeProgressCallback() ``` -------------------------------- ### Default Request Method Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Use the default request method to directly retrieve the data layer object from the API response. This method is suitable when you only need the specific data payload and not the outer response structure (like code or message). ```typescript Net.get("url").request((data) => { //data 就是返回的TestModel对象 }) ``` -------------------------------- ### Define Global Error Interceptor Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Implement a global error interceptor by creating a class that extends NetErrorInterceptor and overriding the httpError method for centralized error handling. ```typescript import { NetError, NetErrorInterceptor } from '@abner/net'; export class MyNetErrorInterceptor extends NetErrorInterceptor { httpError(error: NetError) { //这里进行拦截错误信息 } } ``` -------------------------------- ### Requesting Array Data Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md When the API response's data layer contains an array, use request with a generic type of TestModel[] or Array to directly receive the array. ```typescript Net.get("url").request((data) => { //data 就是返回的TestModel[]数组 }) ``` ```typescript //或者如下 Net.get("url").request>((data) => { //data 就是返回的TestModel数组 }) ``` -------------------------------- ### Request Object Method Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md The requestObject method returns the entire JSON response object, including fields like 'code' and 'message'. It does not require specifying a result tag as it captures the whole structure. ```typescript Net.get("url").requestObject((data) => { //data 为 返回的TestModel对象 }) ``` -------------------------------- ### Accessing NetError Code Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Retrieve the error code from a NetError object using the getCode() method. ```javascript /* * 返回code * */ getCode():number{ return this.code } ``` -------------------------------- ### Local Configuration of Result Tag Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Use the setResultTag method to specify the data field name for a specific request when the API response structure varies and global configuration is not desired or sufficient. ```typescript Net.get("") .setResultTag(["items"]) .request((data) => { }) ``` -------------------------------- ### Accessing NetError Message Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Retrieve the error message from a NetError object using the getMessage() method. ```javascript /* * 返回message * */ getMessage():string{ return this.message } ``` -------------------------------- ### Delete Upload Task Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Deletes an ongoing upload task. The callback receives a boolean indicating success or failure. ```typescript uploadRequest.deleteUploadTask((result) => { if (result) { //成功 } else { //失败 } }) ``` -------------------------------- ### Remove Upload Progress Callback Source: https://github.com/abnerming888/harmonyosnet/blob/master/README.md Removes the progress callback listener from an existing upload request. ```typescript uploadRequest.removeProgressCallback() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.