网络请求封装
This commit is contained in:
parent
8908fa3cc9
commit
15f7f114c4
@ -27,3 +27,5 @@ export { PromptActionClass } from './src/main/ets/components/PromptActionClass'
|
||||
export { RequestDefaultModel,ExpertData } from './src/main/ets/models/RequestDefaultModel'
|
||||
|
||||
export { HdList, HdListController } from './src/main/ets/components/HdList'
|
||||
|
||||
export { hdHttps } from './src/main/ets/utils/expert_request'
|
||||
|
||||
@ -6,19 +6,19 @@ export class BasicConstant {
|
||||
static readonly getzcxy = "http://app.igandan.com/expert_zcxy.jsp";// 注册协议正式地址
|
||||
|
||||
//测试环境
|
||||
// static readonly urlExpertAPI = "https://dev-app.igandan.com/app/expertAPI/";
|
||||
// static readonly urlExpertApp = "https://dev-app.igandan.com//app/expertApp/"
|
||||
// static readonly urlHtml = "http://dev-doc.igandan.com/app/"
|
||||
// static readonly urlImage = "https://dev-doc.igandan.com/app/"
|
||||
// static readonly urlExpert = "https://dev-app.igandan.com/app/expert/"
|
||||
static readonly urlExpertAPI = "https://dev-app.igandan.com/app/expertAPI/";
|
||||
static readonly urlExpertApp = "https://dev-app.igandan.com//app/expertApp/"
|
||||
static readonly urlHtml = "http://dev-doc.igandan.com/app/"
|
||||
static readonly urlImage = "https://dev-doc.igandan.com/app/"
|
||||
static readonly urlExpert = "https://dev-app.igandan.com/app/expert/"
|
||||
|
||||
|
||||
//正式环境
|
||||
static readonly urlExpertAPI = "https://app.igandan.com/app/expertAPI/";
|
||||
static readonly urlExpertApp = "http://app.igandan.com/app/expertApp/"
|
||||
static readonly urlHtml = "http://doc.igandan.com/app/"
|
||||
static readonly urlImage = "http://app.igandan.com/app/"
|
||||
static readonly urlExpert = "http://app.igandan.com/app/expert/"
|
||||
// static readonly urlExpertAPI = "https://app.igandan.com/app/expertAPI/";
|
||||
// static readonly urlExpertApp = "http://app.igandan.com/app/expertApp/"
|
||||
// static readonly urlHtml = "http://doc.igandan.com/app/"
|
||||
// static readonly urlImage = "http://app.igandan.com/app/"
|
||||
// static readonly urlExpert = "http://app.igandan.com/app/expert/"
|
||||
|
||||
|
||||
static readonly getStartpage=BasicConstant.urlExpertApp + "startpage";
|
||||
|
||||
@ -3,10 +3,7 @@ import { authStore } from './auth';
|
||||
import { promptAction, router } from '@kit.ArkUI';
|
||||
import { BusinessError } from '@ohos.base';
|
||||
import { logger } from './logger';
|
||||
import { HashMap } from '@kit.ArkTS';
|
||||
import { CryptoJS } from '@ohos/crypto-js'
|
||||
import { Base64Util } from './Base64Util';
|
||||
import { ChangeUtil } from './ChangeUtil'
|
||||
import uri from '@ohos.uri';
|
||||
|
||||
interface HdRequestOptions {
|
||||
baseURL?: string
|
||||
@ -19,169 +16,23 @@ export interface HdResponse<T> {
|
||||
message: string
|
||||
data: T
|
||||
}
|
||||
export interface TimestampBean {
|
||||
timestamp:string
|
||||
|
||||
|
||||
}
|
||||
class HdHttp {
|
||||
class xx_HdHttp {
|
||||
baseURL: string
|
||||
|
||||
constructor(options: HdRequestOptions) {
|
||||
this.baseURL = options.baseURL || ''
|
||||
}
|
||||
|
||||
private request1<T>(path: string, method: http.RequestMethod = http.RequestMethod.GET, extraDatas:HashMap<string, string>) {
|
||||
const httpInstance = http.createHttp()
|
||||
let fullUrl = this.baseURL + path
|
||||
let promise = httpInstance.request(
|
||||
// 请求url地址
|
||||
fullUrl,
|
||||
{
|
||||
// 请求方式
|
||||
method: http.RequestMethod.POST,
|
||||
// 可选,默认为60s
|
||||
connectTimeout: 60000,
|
||||
// 可选,默认为60s
|
||||
readTimeout: 60000,
|
||||
// 开发者根据自身业务需要添加header字段
|
||||
header: {
|
||||
'Content-Type': 'application/json',
|
||||
'sign':this.getSign(extraDatas)
|
||||
},
|
||||
extraData:ChangeUtil.map2Json(extraDatas)
|
||||
});
|
||||
logger.info('Response JSON.stringify(extraDatas)' + ChangeUtil.map2Json(extraDatas))
|
||||
return promise.then((data) => {
|
||||
logger.info('Response request:' + data.result);
|
||||
if (data.result) {
|
||||
const result = data.result as HdResponse<T>
|
||||
logger.info('Response result:' + result);
|
||||
return result
|
||||
|
||||
}
|
||||
return Promise.reject(data.result)
|
||||
// if (data.responseCode === http.ResponseCode.OK) {
|
||||
// console.info('Response request:' + data.result);
|
||||
//
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
//
|
||||
// }
|
||||
// return Promise.reject(data.result)
|
||||
}
|
||||
|
||||
).catch((err:BusinessError) => {
|
||||
logger.info('Response httpReq request:' + JSON.stringify(err));
|
||||
return Promise.reject(err)
|
||||
|
||||
}).finally(() => {
|
||||
httpInstance.destroy()
|
||||
})
|
||||
|
||||
}
|
||||
private request<T>(path: string, method: http.RequestMethod = http.RequestMethod.POST, extraDatas :HashMap<string, string>) {
|
||||
const httpInstance = http.createHttp()
|
||||
|
||||
const options: http.HttpRequestOptions = {
|
||||
method: http.RequestMethod.POST,
|
||||
// 可选,默认为60s
|
||||
connectTimeout: 60000,
|
||||
// 可选,默认为60s
|
||||
readTimeout: 60000,
|
||||
// 开发者根据自身业务需要添加header字段
|
||||
header: {
|
||||
'Content-Type': 'application/json',
|
||||
'sign':this.getSign(extraDatas)
|
||||
},
|
||||
extraData:ChangeUtil.map2Json(extraDatas)
|
||||
}
|
||||
|
||||
let fullUrl = this.baseURL + path
|
||||
|
||||
|
||||
return httpInstance.request(fullUrl, options).then((res) => {
|
||||
logger.info('Response fullUrl:' +fullUrl+ res.result);
|
||||
const result = res.result as HdResponse<T>
|
||||
return result
|
||||
}).catch((err: BusinessError) => {
|
||||
logger.info(fullUrl+`Response succeeded: ${err}`);
|
||||
promptAction.showToast({ message: err.message || '网络错误' })
|
||||
return Promise.reject(err)
|
||||
}).finally(() => {
|
||||
httpInstance.destroy()
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
private requestafter<T>(path: string, method: http.RequestMethod = http.RequestMethod.GET, extraData?: Object) {
|
||||
const httpInstance = http.createHttp()
|
||||
|
||||
const options: http.HttpRequestOptions = {
|
||||
method: http.RequestMethod.GET,
|
||||
// 可选,默认为60s
|
||||
connectTimeout: 60000,
|
||||
// 可选,默认为60s
|
||||
readTimeout: 60000,
|
||||
// 开发者根据自身业务需要添加header字段
|
||||
header: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
}
|
||||
|
||||
let fullUrl = this.baseURL + path
|
||||
if (method === http.RequestMethod.GET && extraData) {
|
||||
const strArr = Object.keys(extraData)
|
||||
.filter(key => (extraData as HdParams)[key] !== undefined)
|
||||
.map(key => `${key}=${(extraData as HdParams)[key]}`)
|
||||
fullUrl += `?${strArr.join('&')}`
|
||||
} else {
|
||||
options.extraData = extraData
|
||||
}
|
||||
|
||||
return httpInstance.request(fullUrl, options).then((res) => {
|
||||
return Promise.reject(res.result)
|
||||
}).catch((err: BusinessError) => {
|
||||
logger.error(fullUrl+`Response succeeded: ${err}+${err.name}+${err.message}+${err.data}+${err.stack}`);
|
||||
// logger.error(fullUrl, err.code?.toString(), err.message)
|
||||
promptAction.showToast({ message: err.message || '网络错误' })
|
||||
return Promise.reject(err)
|
||||
}).finally(() => {
|
||||
httpInstance.destroy()
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
get<T>(url: string, data?: Object): Promise<HdResponse<T>> {
|
||||
return this.requestafter<T>(url, http.RequestMethod.GET, data)
|
||||
}
|
||||
|
||||
post<T>(url: string, data?: Object): Promise<HdResponse<T>> {
|
||||
return this.requestafter<T>(url, http.RequestMethod.POST, data)
|
||||
}
|
||||
|
||||
put<T>(url: string, data?: Object): Promise<HdResponse<T>> {
|
||||
return this.requestafter<T>(url, http.RequestMethod.PUT, data)
|
||||
}
|
||||
|
||||
delete<T>(url: string, data?: Object): Promise<HdResponse<T>> {
|
||||
return this.requestafter<T>(url, http.RequestMethod.DELETE, data)
|
||||
}
|
||||
posts<T>(url: string, data: HashMap<string, string>): Promise<HdResponse<T>> {
|
||||
return this.request<T>(url, http.RequestMethod.POST, data)
|
||||
}
|
||||
httpReq<T>(url: string, datas: HashMap<string, string>): Promise<HdResponse<T>> {
|
||||
|
||||
private request<T>(path: string, method: http.RequestMethod = http.RequestMethod.GET, extraData?: Object) {
|
||||
// 创建httpRequest对象。
|
||||
let httpRequest = http.createHttp();
|
||||
let url1 = "https://dev-app.igandan.com/app/manager/getSystemTimeStamp";
|
||||
let promise = httpRequest.request(
|
||||
// 请求url地址
|
||||
url1,
|
||||
path,
|
||||
{
|
||||
// 请求方式
|
||||
method: http.RequestMethod.GET,
|
||||
method: method,
|
||||
// 可选,默认为60s
|
||||
connectTimeout: 60000,
|
||||
// 可选,默认为60s
|
||||
@ -189,55 +40,8 @@ class HdHttp {
|
||||
// 开发者根据自身业务需要添加header字段
|
||||
header: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
// 处理响应结果。
|
||||
return promise.then((data) => {
|
||||
if (data.responseCode === http.ResponseCode.OK) {
|
||||
logger.info('Response httpReq:' + data.result);
|
||||
let json:TimestampBean = JSON.parse(data.result.toString()) as TimestampBean;
|
||||
let tp = json.timestamp;
|
||||
datas.set("user_uuid", '');
|
||||
datas.set("client_type", 'A');
|
||||
datas.set("version",'4.0.0' );
|
||||
datas.set('timestamp',tp+'');
|
||||
|
||||
return this.posts<T>(url, datas);
|
||||
}
|
||||
else
|
||||
{
|
||||
return this.posts<T>(url, datas);
|
||||
}
|
||||
}
|
||||
|
||||
).catch((err:BusinessError) => {
|
||||
logger.info('Response httpReq error:' + JSON.stringify(err));
|
||||
return Promise.reject(err);
|
||||
|
||||
}).finally(() => {
|
||||
httpRequest.destroy()
|
||||
})
|
||||
|
||||
}
|
||||
httpReqSimply<T>(url: string) {
|
||||
|
||||
// 创建httpRequest对象。
|
||||
let httpRequest = http.createHttp();
|
||||
|
||||
let promise = httpRequest.request(
|
||||
// 请求url地址
|
||||
url,
|
||||
{
|
||||
// 请求方式
|
||||
method: http.RequestMethod.POST,
|
||||
// 可选,默认为60s
|
||||
connectTimeout: 60000,
|
||||
// 可选,默认为60s
|
||||
readTimeout: 60000,
|
||||
// 开发者根据自身业务需要添加header字段
|
||||
header: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
},
|
||||
extraData:extraData
|
||||
});
|
||||
// 处理响应结果。
|
||||
return promise.then((data) => {
|
||||
@ -245,45 +49,73 @@ class HdHttp {
|
||||
const result = data.result as HdResponse<T>
|
||||
return result
|
||||
}
|
||||
|
||||
).catch((err:BusinessError) => {
|
||||
logger.info('Response httpReq error:' + JSON.stringify(err));
|
||||
return Promise.reject(err);
|
||||
|
||||
}).finally(() => {
|
||||
httpRequest.destroy()
|
||||
})
|
||||
|
||||
}
|
||||
getSign(extraDatas1:HashMap<string, string>): string {
|
||||
let secret= extraDatas1.get("timestamp")
|
||||
if(secret!=null) {
|
||||
let keyValueStr: string = "";
|
||||
let entriesArray: Array<string> = Array.from(extraDatas1.keys());
|
||||
entriesArray.sort();
|
||||
|
||||
let sortedMap:HashMap<string, string> = new HashMap();
|
||||
entriesArray.forEach((value: string, index: number) => {
|
||||
sortedMap.set(value,extraDatas1.get(value));
|
||||
keyValueStr +=value+extraDatas1.get(value)
|
||||
});
|
||||
keyValueStr = keyValueStr.replace(" ", "");
|
||||
keyValueStr = keyValueStr + CryptoJS.MD5(secret).toString();
|
||||
let Md5keyValueStr: string = CryptoJS.MD5(keyValueStr).toString();
|
||||
let base64Str:string=Base64Util.encodeToStrSync(Md5keyValueStr);
|
||||
return base64Str;
|
||||
}
|
||||
else
|
||||
{
|
||||
return '';
|
||||
// const httpInstance = http.createHttp()
|
||||
// const options: http.HttpRequestOptions = {
|
||||
// header: {
|
||||
// 'Content-Type': 'application/json;charset=utf-8',
|
||||
// 'Content-Language': 'zh_CN',
|
||||
// connectTimeout: 60000,
|
||||
// readTimeout: 60000,
|
||||
// },
|
||||
// method
|
||||
// }
|
||||
// let fullUrl = this.baseURL + path
|
||||
// if (method === http.RequestMethod.GET && extraData) {
|
||||
// const strArr = Object.keys(extraData)
|
||||
// .filter(key => (extraData as HdParams)[key] !== undefined)
|
||||
// .map(key => `${key}=${(extraData as HdParams)[key]}`)
|
||||
// fullUrl += `?${strArr.join('&')}`
|
||||
// } else {
|
||||
// options.extraData = JSON.stringify(extraData);
|
||||
// }
|
||||
// return httpInstance.request(fullUrl, options).then((res) => {
|
||||
// if (res.result) {
|
||||
// const result = res.result as HdResponse<T>
|
||||
// console.log('请求成功:',JSON.stringify(res.result));
|
||||
// if (result.code === 10000) {
|
||||
// logger.info(fullUrl, JSON.stringify(res.result).substring(0, 200))
|
||||
// return result
|
||||
// }
|
||||
// if (result.code === 401) {
|
||||
// authStore.delUser()
|
||||
// router.pushUrl({
|
||||
// url: 'pages/LoginPage/LoginPage'
|
||||
// }, router.RouterMode.Single)
|
||||
// throw new Error('登录过期')
|
||||
// }
|
||||
// }
|
||||
// return Promise.reject(res.result)
|
||||
// }).catch((err: BusinessError) => {
|
||||
// logger.error(fullUrl, err.code?.toString(), err.message)
|
||||
// promptAction.showToast({ message: err.message || '网络错误' })
|
||||
// return Promise.reject(err)
|
||||
// }).finally(() => {
|
||||
// httpInstance.destroy()
|
||||
// })
|
||||
}
|
||||
|
||||
get<T>(url: string, data?: Object): Promise<HdResponse<T>> {
|
||||
return this.request<T>(url, http.RequestMethod.GET, data)
|
||||
}
|
||||
|
||||
}
|
||||
post<T>(url: string, data?: Object): Promise<HdResponse<T>> {
|
||||
return this.request<T>(url, http.RequestMethod.POST, data)
|
||||
}
|
||||
|
||||
put<T>(url: string, data?: Object): Promise<HdResponse<T>> {
|
||||
return this.request<T>(url, http.RequestMethod.PUT, data)
|
||||
}
|
||||
|
||||
delete<T>(url: string, data?: Object): Promise<HdResponse<T>> {
|
||||
return this.request<T>(url, http.RequestMethod.DELETE, data)
|
||||
}
|
||||
}
|
||||
|
||||
export const hdHttp = new HdHttp({ baseURL: '' })
|
||||
|
||||
|
||||
|
||||
|
||||
export const hdHttps = new xx_HdHttp({ baseURL: '' })
|
||||
@ -270,13 +270,6 @@ class HdHttp {
|
||||
}
|
||||
}
|
||||
|
||||
interface UploadImageParams {
|
||||
uuid:string,
|
||||
userName:string,
|
||||
photo:string,
|
||||
type:string
|
||||
}
|
||||
|
||||
export const hdHttp = new HdHttp({ baseURL: '' })
|
||||
|
||||
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { hdHttp, HdResponse,BasicConstant,ExpertData, authStore, ChangeUtil } from '@itcast/basic'
|
||||
import { hdHttp, HdResponse,BasicConstant,ExpertData, authStore, ChangeUtil,hdHttps } from '@itcast/basic'
|
||||
import HashMap from '@ohos.util.HashMap'
|
||||
import { BusinessError } from '@kit.BasicServicesKit';
|
||||
import { promptAction, router } from '@kit.ArkUI'
|
||||
@ -43,6 +43,8 @@ interface UploadAvatarResponse {
|
||||
|
||||
@Component
|
||||
export struct EditUserDataComp {
|
||||
@Prop @Watch('pageShow') refreshStatus:boolean = false;
|
||||
|
||||
@State photoPath:string = BasicConstant.urlImage+authStore.getUser().photo;
|
||||
@State name:string = authStore.getUser().realName;
|
||||
@State sex:string = authStore.getUser().sex == 0 ? '男' : '女';
|
||||
@ -75,10 +77,16 @@ export struct EditUserDataComp {
|
||||
this.initPositionPickerDialog();
|
||||
this.initCerficatePhotoDialog();
|
||||
this.initDiseaseSheetDIalog();
|
||||
this.uploadUserDataAction();
|
||||
// this.uploadUserDataAction();
|
||||
console.log('用户资料:'+authStore.getUser().specialy);
|
||||
}
|
||||
|
||||
pageShow() {
|
||||
if (this.refreshStatus) {
|
||||
this.uploadUserDataAction();
|
||||
}
|
||||
}
|
||||
|
||||
// 添加public修饰符暴露方法
|
||||
public refreshData() {
|
||||
this.uploadUserDataAction();
|
||||
@ -93,13 +101,25 @@ export struct EditUserDataComp {
|
||||
if(json.code == 1 && json.expert && typeof json.expert === 'object') {
|
||||
authStore.updateUser(json.expert)
|
||||
this.arrToStringSpecialy(json.specialy);
|
||||
console.log('用户信息成功:', authStore.getUser().intro);
|
||||
this.photoPath = authStore.getUser().photo;
|
||||
this.name = authStore.getUser().realName;
|
||||
this.sex = authStore.getUser().sex == 0 ? '男' : '女';
|
||||
this.birthday = authStore.getUser().birthDate;
|
||||
this.phone = authStore.getUser().mobile;
|
||||
this.email = authStore.getUser().email;
|
||||
this.hospatilName = authStore.getUser().hospitalName;
|
||||
this.officeName = authStore.getUser().officeName;
|
||||
this.officePhone = authStore.getUser().officePhone;
|
||||
this.positionName = authStore.getUser().positionName;
|
||||
this.certificate = authStore.getUser().certificate;
|
||||
this.certificatePhoto = BasicConstant.urlImage+authStore.getUser().certificateImg;
|
||||
this.intro = authStore.getUser().intro;
|
||||
} else {
|
||||
console.error('用户信息失败:'+json.message)
|
||||
promptAction.showToast({ message: json.message, duration: 1000 })
|
||||
}
|
||||
}).catch((err: BusinessError) => {
|
||||
console.info(`Response login fail222222222222222: ${err}`);
|
||||
console.info(`Response fails: ${err}`);
|
||||
})
|
||||
}
|
||||
|
||||
@ -162,25 +182,34 @@ export struct EditUserDataComp {
|
||||
controller:this.officePickerDialog,
|
||||
officeSelected: (name:string , uuid:string) => {
|
||||
this.officeName = name;
|
||||
hdHttp.post<string>(this.updateDataUrl, {
|
||||
uuid: authStore.getUser().uuid,
|
||||
userName: authStore.getUser().userName,
|
||||
hdHttps.post<null>(this.updateDataUrl, {
|
||||
officeName: name,
|
||||
officeUuid:uuid,
|
||||
type:'2'
|
||||
} as updateExtraData).then(async (res: HdResponse<string>) => {
|
||||
type:'2',
|
||||
userName: authStore.getUser().userName,
|
||||
uuid: authStore.getUser().uuid,
|
||||
} as updateExtraData).then(res => {
|
||||
let json:callBackData = JSON.parse(res+'') as callBackData;
|
||||
if(json.code == 1 && json.data && typeof json.data === 'object') {
|
||||
authStore.updateUser(json.data)
|
||||
this.arrToStringSpecialy(json.special);
|
||||
console.log('更新用户信息科室成功:', authStore.getUser().intro);
|
||||
} else {
|
||||
console.error('更新用户信息科室失败:'+json.message)
|
||||
promptAction.showToast({ message: json.message, duration: 1000 })
|
||||
}
|
||||
}).catch((err: BusinessError) => {
|
||||
console.info(`更新用户信息职称科室失败: ${err}`);
|
||||
})
|
||||
// hdHttp.post<string>(this.updateDataUrl, {
|
||||
// uuid: authStore.getUser().uuid,
|
||||
// userName: authStore.getUser().userName,
|
||||
// officeName: name,
|
||||
// officeUuid:uuid,
|
||||
// type:'2'
|
||||
// } as updateExtraData).then(async (res: HdResponse<string>) => {
|
||||
// let json:callBackData = JSON.parse(res+'') as callBackData;
|
||||
// if(json.code == 1 && json.data && typeof json.data === 'object') {
|
||||
// authStore.updateUser(json.data)
|
||||
// this.arrToStringSpecialy(json.special);
|
||||
// console.log('更新用户信息科室成功:', authStore.getUser().intro);
|
||||
// } else {
|
||||
// console.error('更新用户信息科室失败:'+json.message)
|
||||
// promptAction.showToast({ message: json.message, duration: 1000 })
|
||||
// }
|
||||
// }).catch((err: BusinessError) => {
|
||||
// console.info(`更新用户信息职称科室失败: ${err}`);
|
||||
// })
|
||||
}
|
||||
}),
|
||||
alignment: DialogAlignment.Bottom,
|
||||
|
||||
@ -5,16 +5,20 @@ import { EditUserDataComp } from 'mypage'
|
||||
@Component
|
||||
struct EditUserDataPage {
|
||||
// 使用$符号引用子组件
|
||||
@State editUserDataCompRef: EditUserDataComp | null = null;
|
||||
@State refreshStatus: boolean = false;
|
||||
|
||||
onPageShow(): void {
|
||||
this.editUserDataCompRef?.refreshData();
|
||||
this.refreshStatus = true;
|
||||
}
|
||||
|
||||
onPageHide(): void {
|
||||
this.refreshStatus = false;
|
||||
}
|
||||
|
||||
build() {
|
||||
Column(){
|
||||
HdNav({ title: '个人资料', showRightIcon: false, hasBorder: true });
|
||||
EditUserDataComp()
|
||||
EditUserDataComp({refreshStatus:this.refreshStatus})
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user