ini myapp and review rest api

This commit is contained in:
2024-08-27 19:11:26 +08:00
parent 58ee459459
commit ff8c5714d9
7 changed files with 82 additions and 17 deletions

View File

@@ -1,5 +1,8 @@
import { Log } from '@devwiki/base/Index';
import axios, { AxiosError, AxiosResponse } from '@ohos/axios'
import http from '@ohos.net.http';
const TAG = '[RestAPIPage]'
@Entry({routeName: "RestAPIPage"})
@Component
@@ -8,29 +11,37 @@ export struct RestAPIPage {
@State viewModel: RestAPIViewModel = new RestAPIViewModel();
build() {
Row() {
Column() {
Flex({
justifyContent: FlexAlign.SpaceBetween
justifyContent: FlexAlign.Start,
direction: FlexDirection.Column,
alignItems: ItemAlign.Center
}) {
Button("Get").onClick(() =>{
this.viewModel.getServerVersion();
})
Button("GetByAxios").onClick(() =>{
this.viewModel.getServerVersionByAxios();
}).margin({top: 20})
Text(this.viewModel.serverVersion).backgroundColor(Color.Blue).flexGrow(1);
}
}.justifyContent(FlexAlign.Start).alignItems(VerticalAlign.Center).width('80%').backgroundColor(Color.Green)
Button("GetByHttp").onClick(() =>{
this.viewModel.getServerVersionByHttp();
}).margin({top: 20})
Text(this.viewModel.serverVersion).margin({top: 20})
}.width('80%')
}.width('100%')
}
}
class RestAPIViewModel {
readonly viewUrl: string = 'https://music.devwiki.net/rest/ping.view?v=1.16.1&c=myapp&f=json';
serverVersion: string = '123'
async getServerVersion() {
async getServerVersionByAxios() {
this.serverVersion = ''
await axios({
method: "post",
url: 'https://music.devwiki.net/rest/ping.view?v=1.16.1&c=myapp&f=json'
url: this.viewUrl
}).then((response: AxiosResponse) => {
if (response.status == 200) {
let version:string = response.data['subsonic-response']['serverVersion'];
@@ -41,4 +52,22 @@ class RestAPIViewModel {
Log.e(error.message);
})
}
getServerVersionByHttp() {
this.serverVersion = ''
let httpRequest = http.createHttp();
let option:http.HttpRequestOptions = {
method: http.RequestMethod.GET
};
httpRequest.request(this.viewUrl, option, (error, resp) =>{
if (!error) {
Log.i(TAG, 'request http code:' + resp.responseCode)
let version:string = resp.result['subsonic-response']['serverVersion'];
this.serverVersion = version;
} else {
Log.e(TAG, `request failed, code:${error.code}, message:${error.message}`)
}
httpRequest.destroy();
});
}
}