Function Introduction:¶
Send a POST request to upload data to the server and obtain the result, referring to the documentation HTTP Data Request.
Key Knowledge Points:¶
- Familiar with sending asynchronous POST requests.
- Parse returned JSON-formatted data.
Usage Environment:¶
- API 9
- DevEco Studio 4.0 Release
- Windows 11
- Stage Model
- ArkTS Language
Required Permissions:¶
- ohos.permission.INTERNET
Core Code Snippet:¶
Send an HTTP asynchronous request, obtain the response result, and finally parse the JSON data function:
async onRequest() {
this.enabledBtn = false;
let httpRequest = http.createHttp();
// Asynchronous request
let promise = httpRequest.request(this.llmUrl, {
method: http.RequestMethod.POST,
header: { 'Content-Type': 'application/json; charset=utf-8' },
// Data to send
extraData: { "prompt": this.text }
})
promise.then((data) => {
console.info('Return result: ' + data.result)
// Convert result to JSON
let result = JSON.parse(data.result.toString())
// Parse the result
this.response = result['response']
this.enabledBtn = true
}).catch((err) => {
console.error('Error message: ' + JSON.stringify(err))
})
}
Complete Code:¶
import http from '@ohos.net.http';
@Entry
@Component
struct Index {
@State text: string = 'What is your name?'
@State response: string = ''
@State enabledBtn: boolean = true
private llmUrl: string = "http://xxx.xxxxx"
build() {
RelativeContainer() {
Text(this.response)
// Left alignment
.textAlign(TextAlign.Start)
.width("100%")
// Allow text copying
.copyOption(CopyOptions.InApp)
.padding({ top: 10, left: 5, right: 5 })
// Show ellipsis for overflow
.textOverflow({ overflow: TextOverflow.Ellipsis })
.maxLines(20)
.alignRules({
top: { anchor: '__container__', align: VerticalAlign.Top },
})
.id('text1')
Row() {
TextInput({ placeholder: 'Please enter the text content to send', text: this.text })
.width("70%")
.height("100%")
.onChange((value: string) => {
this.text = value
})
Button("Send")
.fontSize(16)
.width("25%")
.height("100%")
.margin({ left: 10 })
.onClick(() => {
this.onRequest()
})
.enabled(this.enabledBtn)
}
.width("100%")
.height(40)
.margin({ bottom: 10 })
.alignRules({
// Align to the bottom of the parent component
bottom: { anchor: '__container__', align: VerticalAlign.Bottom },
})
.id("row1")
}
.width("100%")
.height("100%")
}
async onRequest() {
this.enabledBtn = false;
let httpRequest = http.createHttp();
// Asynchronous request
let promise = httpRequest.request(this.llmUrl, {
method: http.RequestMethod.POST,
header: { 'Content-Type': 'application/json; charset=utf-8' },
// Data to send
extraData: { "prompt": this.text }
})
promise.then((data) => {
console.info('Return result: ' + data.result)
// Convert result to JSON
let result = JSON.parse(data.result.toString())
// Parse the result
this.response = result['response']
}).catch((err) => {
console.error('Error message: ' + JSON.stringify(err))
}).finally(()=>{
this.enabledBtn = true
})
}
}