前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >鸿蒙应用开发-发送POST请求并获取结果

鸿蒙应用开发-发送POST请求并获取结果

作者头像
夜雨飘零
发布2024-05-26 16:10:07
1460
发布2024-05-26 16:10:07
举报
文章被收录于专栏:CSDN博客CSDN博客

功能介绍:

发送POST请求,上传数据到服务器并获取结果,参考文档HTTP数据请求

知识点:

  1. 熟悉发送POST异步请求。
  2. 解析返回的JSON格式数据。

使用环境:

  • API 9
  • DevEco Studio 4.0 Release
  • Windows 11
  • Stage模型
  • ArkTS语言

所需权限:

  1. ohos.permission.INTERNET

核心代码片段,发送HTTP异步请求,并获取放回结果,最后解析JSON数据函数:

代码语言:javascript
复制
  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))
  })
}

完整代码:

代码语言:javascript
复制
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
    })
  }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-01-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档