Skip to content

Commit

Permalink
v2.0
Browse files Browse the repository at this point in the history
网络请求框架+数据封装
  • Loading branch information
PGzxc committed Nov 7, 2023
1 parent a9f1e8e commit 6d0b19e
Show file tree
Hide file tree
Showing 29 changed files with 959 additions and 12 deletions.
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,13 @@
### 3.1 v1.0

* 启动页+底部导航框架
* 底部导航框架使用:Tabs+tabBar
* 底部导航框架使用:Tabs+tabBar

### 3.2 v2.0

* 网络请求框架(HttpService(网络请求封装)+ResponseResult(返回结果)+HttpRequest(网络请求Promise)+HttpConfig(相关配置))
* Stage模型,在module.json5配置文件中声明权限(比如网络权限`ohos.permission.INTERNET`)
* bean包将接口返回结果封装成数据Bean
* viewmodel中Promise+async解析结果数据为Bean
* Page页面aboutToAppear(页面即将显示)方法中调用viewmodel中的接口

193 changes: 193 additions & 0 deletions entry/src/main/ets/api/HttpConfig.ets
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
/*
* @desc:网络请求相关配置
*/

export default class HttpConfig {
/**
* The host address of the server.
*/
static readonly baseURL: string = 'https://www.wanandroid.com/';

//1-首页
static readonly bannerUrl: string = HttpConfig.baseURL + 'banner/json';
static readonly articleTopUrl: string = HttpConfig.baseURL + 'article/top/json';
static readonly articleListUrl: string = HttpConfig.baseURL + 'article/list'; // /0/json

//2-导航
static readonly treeUrl: string = HttpConfig.baseURL + 'tree/json';
static readonly treeListUrl: string = HttpConfig.baseURL + 'article/list';

//3-项目
static readonly projectUrl: string = HttpConfig.baseURL + 'project/tree/json';
static readonly projectListUrl: string = HttpConfig.baseURL + 'project/list';

//4-消息-需要登录
static readonly msgUnreadUrl: string = HttpConfig.baseURL + 'message/lg/count_unread/json';
static readonly msgReadUrl: string = HttpConfig.baseURL + 'message/lg/readed_list/'; //message/lg/readed_list/%s/json

//5-用户信息
static readonly userInfUrl: string = HttpConfig.baseURL + 'user/lg/userinfo/json';

//6-登录、注册、退出
static readonly loginUrl: string = HttpConfig.baseURL + 'user/login';
static readonly registerUrl: string = HttpConfig.baseURL + 'user/register';
static readonly logoutUrl: string = HttpConfig.baseURL + 'user/logout/json';

/**
* The request success status code.
*/
static readonly SERVER_CODE_SUCCESS: number = 0;

/**
* The off set coefficient.
*/
static readonly Y_OFF_SET_COEFFICIENT: number = 0.1;

/**
* The page size.
*/
static readonly PAGE_SIZE: number = 10;

/**
* The refresh and load height.
*/
static readonly CUSTOM_LAYOUT_HEIGHT: number = 70;

/**
* Gt tab data current page.
*/
static readonly GET_TAB_DATA_CURRENT_PAGE: number = 1;

/**
* Http request success status code.
*/
static readonly HTTP_CODE_200: number = 200;
static readonly HTTP_CODE_0: number = 0;
/**
* The animation delay time.
*/
static readonly DELAY_ANIMATION_DURATION: number = 300;

/**
* The delay time.
*/
static readonly DELAY_TIME: number = 1000;

/**
* The animation duration.
*/
static readonly ANIMATION_DURATION: number = 2000;

/**
* The http timeout duration.
*/
static readonly HTTP_READ_TIMEOUT: number = 10000;

/**
* Content maxLine.
*/
static readonly CONTENT_MAX_LINE: number = 3;

/**
* List space.
*/
static readonly LIST_SPACE: number = 12;

/**
* Item img space.
*/
static readonly ITEM_IMG_SPACE: number = 8;

/**
* Type font weight.
*/
static readonly TYPE_FONT_WEIGHT: number = 700;

/**
* Title font weight.
*/
static readonly TITLE_FONT_WEIGHT: number = 500;

/**
* Desc font weight.
*/
static readonly DESC_FONT_WEIGHT: number = 400;

/**
* Type aspect ratio.
*/
static readonly TYPE_ASPECT_RATIO: number = 2;

/**
* Desc opacity.
*/
static readonly DESC_OPACITY: number = 0.6;

/**
* 100 percent.
*/
static readonly FULL_PERCENT: string = '100%';

/**
* Divider width.
*/
static readonly DIVIDER_WIDTH: string = '90%';

/**
* Release title.
*/
static readonly RELEASE_TITLE: string = '新闻发布';
}

/**
* The RefreshConstant constants.
*/
export const enum RefreshConstant {
DELAY_PULL_DOWN_REFRESH = 50,
CLOSE_PULL_DOWN_REFRESH_TIME = 150,
DELAY_SHRINK_ANIMATION_TIME = 500
}

/**
* The refresh state enum.
*/
export const enum RefreshState {
DropDown = 0,
Release = 1,
Refreshing = 2,
Success = 3,
Fail = 4
}

/**
* The newsList state enum.
*/
export const enum PageState {
Loading = 0,
Success = 1,
Fail = 2
}

/**
* The file upload state enum.
*/
export const enum UploadingState {
COMPLETE = 'complete',
FAIL = 'fail'
}

/**
* The request method enum.
*/
export const enum RequestMethod {
POST = 'POST',
GET = 'GET'
}

/**
* The request content type enum.
*/
export const enum ContentType {
JSON = 'application/json',
FORM = 'multipart/form-data'
}
42 changes: 42 additions & 0 deletions entry/src/main/ets/api/HttpRequest.ets
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import HttpConfig from './HttpConfig';
import { httpRequestGet, httpRequestPost } from './HttpService';
/**
* @desc:Http网络请求
*/

//1-home(首页)
const bannerReq = () => httpRequestGet(HttpConfig.bannerUrl);
const articleTopReq = () => httpRequestGet(HttpConfig.articleTopUrl);
const articleListReq = (page: number) => httpRequestGet(`${HttpConfig.articleListUrl}/${page}/json`);

//2-nav(导航)
const treeReq = () => httpRequestGet(HttpConfig.treeUrl);
const treeListReq = (page: number, cid: number) => httpRequestGet(`${HttpConfig.treeListUrl}/${page}/json?cid=${cid}`);

//3-project(项目)
const projectReq = () => httpRequestGet(HttpConfig.projectUrl);
const projectListReq = (page: number, cid: number) => httpRequestGet(`${HttpConfig.projectListUrl}/${page}/json?cid=${cid}`);

//4-msg(消息)
const msgUnReadReq = () =>httpRequestGet(HttpConfig.msgUnreadUrl);
const msgReadReq = (page: number)=>httpRequestGet(`${HttpConfig.msgReadUrl}/${page}/json`);

//5-me(我的)

const userReq = () => httpRequestGet(HttpConfig.userInfUrl);


//6-login(登录)、register(注册)
const loginReq = (username:string,password:string) =>httpRequestPost(HttpConfig.loginUrl,{'username':username,'password':password});
const registerReq = (username:string,password:string,repassword:string) =>httpRequestPost(HttpConfig.loginUrl,{'username':username,'password':password,'repassword':repassword});
const logoutReq = () => httpRequestGet(HttpConfig.logoutUrl);


export {
bannerReq, articleTopReq, articleListReq,
treeReq,treeListReq,
projectReq,projectListReq,
msgUnReadReq,msgReadReq,
userReq,
loginReq,registerReq,logoutReq
}
78 changes: 78 additions & 0 deletions entry/src/main/ets/api/HttpService.ets
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* 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.
* @desc:网络请求工具类
*/

import http from '@ohos.net.http';
import ResponseResult from './ResponseResult';
import HttpConfig, { ContentType } from './HttpConfig';

/**
* Initiate an HTTP GET request to the specified URL.
*
* @param url URL for initiating an HTTP request.
*/
export function httpRequestGet(url: string) {
return httpRequest(url, http.RequestMethod.GET);
}

/**
* Initiate an HTTP POST request to the specified URL.
*
* @param url URL for initiating an HTTP request
* @param newsData Additional data of the request
* @returns
*/
export function httpRequestPost(url: string, params: Object) {
return httpRequest(url, http.RequestMethod.POST, params);
}

/**
* Initiates an HTTP request to a given URL.
*
* @param url URL for initiating an HTTP request
* @param method Request method.
* @param extraData Additional data of the request.
* @returns Returns {@link ResponseResult}.
*/
function httpRequest(url: string, method: http.RequestMethod, params?: Object): Promise<ResponseResult> {
let httpRequest = http.createHttp();
let responseResult = httpRequest.request(url, {
method: method,
header: { 'Content-Type': ContentType.JSON },
readTimeout: HttpConfig.HTTP_READ_TIMEOUT,
connectTimeout: HttpConfig.HTTP_READ_TIMEOUT,
extraData: params
});
let serverData = new ResponseResult();
// Processes the data and returns.
return responseResult.then((value: http.HttpResponse) => {
if (value.responseCode === HttpConfig.HTTP_CODE_200) {
// Obtains the returned data.
let result = `${value.result}`;
let resultJson: ResponseResult = JSON.parse(result);
if (resultJson.errorCode === HttpConfig.SERVER_CODE_SUCCESS) {
serverData.data = resultJson.data;
}
serverData.errorCode = resultJson.errorCode;
serverData.errorMsg = resultJson.errorMsg;
} else {
serverData.errorMsg = `${$r('app.string.http_error_message')}&${value.responseCode}`;
}
return serverData;
}).catch(() => {
serverData.errorMsg = $r('app.string.http_error_message');
return serverData;
});
}
25 changes: 25 additions & 0 deletions entry/src/main/ets/api/ResponseResult.ets
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* @desc:网络请求返回结果
*/
export default class ResponseResult {
/**
* Code returned by the network request: success, fail.
*/
errorCode: number;

/**
* Message returned by the network request.
*/
errorMsg: string | Resource;

/**
* Data returned by the network request.
*/
data: string | Object | ArrayBuffer;

constructor() {
this.errorCode = 0;
this.errorMsg = '';
this.data = '';
}
}
Loading

0 comments on commit 6d0b19e

Please sign in to comment.