|
|
@@ -0,0 +1,67 @@
|
|
|
+import { rcp } from '@kit.RemoteCommunicationKit';
|
|
|
+import { Constants } from '../constants';
|
|
|
+import { common } from '@kit.AbilityKit';
|
|
|
+import { preferences } from '@kit.ArkData';
|
|
|
+/**
|
|
|
+ * http请求工具类
|
|
|
+ */
|
|
|
+export class Api{
|
|
|
+ // private static router:NavPathStack
|
|
|
+
|
|
|
+ private static getSession(options:rcp.SessionConfiguration,context: common.Context,):rcp.Session{
|
|
|
+ options.baseAddress = Constants.BASE_URL;
|
|
|
+ //添加拦截器
|
|
|
+ options.interceptors = [new RequestTokenInterceptor(context)]
|
|
|
+ return rcp.createSession(options)
|
|
|
+ }
|
|
|
+
|
|
|
+ public static async getRequest(url:string,context: common.Context,options:rcp.SessionConfiguration={}):Promise<rcp.Response>{
|
|
|
+ let session:rcp.Session = Api.getSession(options,context)
|
|
|
+ let res = await session.get(url)
|
|
|
+ session.close()
|
|
|
+ return res
|
|
|
+ }
|
|
|
+
|
|
|
+ public static async postRequest(url:string,context: common.Context,options:rcp.SessionConfiguration={},content?:rcp.RequestContent):Promise<rcp.Response>{
|
|
|
+ let session:rcp.Session = Api.getSession(options,context)
|
|
|
+ let res = await session.post(url,content)
|
|
|
+ session.close()
|
|
|
+ return res
|
|
|
+ }
|
|
|
+
|
|
|
+ public static async deleteRequest(url:string,context: common.Context,options:rcp.SessionConfiguration={}):Promise<rcp.Response>{
|
|
|
+ let session:rcp.Session = Api.getSession(options,context)
|
|
|
+ let res = await session.delete(url)
|
|
|
+ session.close()
|
|
|
+ return res
|
|
|
+ }
|
|
|
+
|
|
|
+ public static async putRequest(url:string,context: common.Context,options:rcp.SessionConfiguration={},content?:rcp.RequestContent):Promise<rcp.Response>{
|
|
|
+ let session:rcp.Session = Api.getSession(options,context)
|
|
|
+ let res = await session.put(url,content)
|
|
|
+ session.close()
|
|
|
+ return res
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/**
|
|
|
+ * 给请求添加token的拦截器
|
|
|
+ */
|
|
|
+class RequestTokenInterceptor implements rcp.Interceptor{
|
|
|
+ private appContext:common.Context
|
|
|
+
|
|
|
+ constructor(context: common.Context) {
|
|
|
+ this.appContext = context;
|
|
|
+ }
|
|
|
+
|
|
|
+ intercept(context: rcp.RequestContext, next: rcp.RequestHandler): Promise<rcp.Response> {
|
|
|
+ let dataPreferences = preferences.getPreferencesSync(this.appContext, {
|
|
|
+ name:'tokenStore'
|
|
|
+ });
|
|
|
+ let token = dataPreferences?.getSync('token',"") as string;
|
|
|
+ context.request.headers = {
|
|
|
+ "Authorization":token
|
|
|
+ }
|
|
|
+ return next.handle(context)
|
|
|
+ }
|
|
|
+}
|