通用类
import http from '@ohos.net.http' ;
const Test: boolean = true ;
const Url: string = Test ? 'http://api.林.cn/' : 'http://api.林.cn/' ; export function request ( api: string , method: string , data: any , token: string = '' ) : Promise < any > { return new Promise ( ( resolve, reject) => { const url = Url + api; const httpRequest = http. createHttp ( ) ; const requestMethod = getRequestMethod ( method) ; const customHeaders = { 'Content-Type' : 'application/json' , 'Authorization' : token } ; const promise = httpRequest. request ( url, { method: requestMethod, extraData: data, connectTimeout: 60000 , readTimeout: 60000 , header: { ... customHeaders } } ) ; promise. then ( ( responseData) => { if ( responseData. responseCode === http. ResponseCode. OK ) { resolve ( responseData) ; } else { console . error ( '错误 - 响应代码: ' + responseData. responseCode) ; reject ( new Error ( 'HTTP 请求失败,响应代码为 ' + responseData. responseCode) ) ; } } ) . catch ( ( error) => { console . error ( '错误: ' + JSON . stringify ( error) ) ; reject ( error) ; } ) ; } ) ;
}
function getRequestMethod ( method: string ) : http. RequestMethod { switch ( method. toLowerCase ( ) ) { case 'get' : return http. RequestMethod. GET ; case 'post' : return http. RequestMethod. POST ; case 'put' : return http. RequestMethod. PUT ; case 'delete' : return http. RequestMethod. DELETE ; default : throw new Error ( ` 不支持的 HTTP 方法: ${ method} ` ) ; }
}
调用方式
import { request } from '../tools/httpUtils' ;
@ Entry
@ Component
struct Index { @ State message: string = '啾啾救援' build ( ) { Row ( ) { Column ( ) { Image ( "http://www.jjsos.cn/images/menu_logo.png" ) . width ( 300 ) . interpolation ( ImageInterpolation. High) Text ( this . message) . fontSize ( 50 ) . fontWeight ( FontWeight. Bold) Button ( '确定' ) . fontSize ( 30 ) . backgroundColor ( "#000" ) . onClick ( ( ) => { this . message= "JJSOS" } ) TextInput ( { placeholder: '用户名' } ) . type ( InputType. PhoneNumber) TextInput ( { placeholder: '密码' } ) . type ( InputType. Password) Button ( '确定登陆' ) . onClick ( ( ) => { const requestData = { "type" : "1" , "username" : "13176630659" , "password" : "123456" } ; const authToken: string = "" const apiEndpoint = 'v2/auth/get-access-token' ; request ( apiEndpoint, 'post' , requestData, authToken) . then ( ( responseData) => { console . log ( 'Response:' , responseData) ; } ) . catch ( ( error) => { console . error ( 'Error:' , error) ; } ) ; } ) } . width ( '100%' ) . backgroundColor ( "#aaa" ) } . height ( '100%' ) . backgroundColor ( "#aaa" ) }
} function authToken ( apiEndpoint: string , arg1: string , requestData: { type: string ; username: string ; password: string ; } , authToken: any ) {
throw new Error ( 'Function not implemented.' ) ;
}