功能介紹:
發送POST請求,上傳數據到服務器並獲取結果,參考文檔HTTP數據請求。
知識點:
- 熟悉發送POST異步請求。
- 解析返回的JSON格式數據。
使用環境:
- API 9
- DevEco Studio 4.0 Release
- Windows 11
- Stage模型
- ArkTS語言
所需權限:
- ohos.permission.INTERNET
核心代碼片段,發送HTTP異步請求,並獲取放回結果,最後解析JSON數據函數:
async onRequest() {
this.enabledBtn = false;
let httpRequest = http.createHttp();
// 異步請求
let promise = httpRequest.request(this.llmUrl, {
method: http.RequestMethod.POST,
header: { 'Content-Type': 'application/json; charset=utf-8' },
// 發送的數據
extraData: { "prompt": this.text }
})
promise.then((data) => {
console.info('返回結果: ' + data.result)
// 結果轉JSON
let result = JSON.parse(data.result.toString())
// 解析結果
this.response = result['response']
this.enabledBtn = true
}).catch((err) => {
console.error('錯誤信息:' + JSON.stringify(err))
})
}
完整代碼:
import http from '@ohos.net.http';
@Entry
@Component
struct Index {
@State text: string = '你叫什麼名字?'
@State response: string = ''
@State enabledBtn: boolean = true
private llmUrl: string = "http://xxx.xxxxx"
build() {
RelativeContainer() {
Text(this.response)
// 左對齊
.textAlign(TextAlign.Start)
.width("100%")
// 允許複製文本
.copyOption(CopyOptions.InApp)
.padding({top:10, left:5, right:5})
// 超出部分顯示省略號
.textOverflow({ overflow: TextOverflow.Ellipsis })
.maxLines(20)
.alignRules({
top: { anchor: '__container__', align: VerticalAlign.Top },
})
.id('text1')
Row() {
TextInput({ placeholder: '請輸入要發送的文本內容', text: this.text })
.width("70%")
.height("100%")
.onChange((value: string) => {
this.text = value
})
Button("發送")
.fontSize(16)
.width("25%")
.height("100%")
.margin({ left: 10 })
.onClick(() => {
this.onRequest()
})
.enabled(this.enabledBtn)
}
.width("100%")
.height(40)
.margin({ bottom: 10 })
.alignRules({
// 相對父組件底部對齊
bottom: { anchor: '__container__', align: VerticalAlign.Bottom },
})
.id("row1")
}
.width("100%")
.height("100%")
}
async onRequest() {
this.enabledBtn = false;
let httpRequest = http.createHttp();
// 異步請求
let promise = httpRequest.request(this.llmUrl, {
method: http.RequestMethod.POST,
header: { 'Content-Type': 'application/json; charset=utf-8' },
// 發送的數據
extraData: { "prompt": this.text }
})
promise.then((data) => {
console.info('返回結果: ' + data.result)
// 結果轉JSON
let result = JSON.parse(data.result.toString())
// 解析結果
this.response = result['response']
}).catch((err) => {
console.error('錯誤信息:' + JSON.stringify(err))
}).finally(()=>{
this.enabledBtn = true
})
}
}