HarmonyOS 鸿蒙Next http怎么解析返回的数据,并提取其中的token

发布于 1周前 作者 sinazl 最后一次编辑是 5天前 来自 鸿蒙OS

HarmonyOS 鸿蒙Next http怎么解析返回的数据,并提取其中的token

import http from '@ohos.net.http';
import { JSON } from '@kit.ArkTS';

class Header {
  public contentType: string;

  constructor(contentType: string) {
    this.contentType = contentType
  }
}

let httpRequest = http.createHttp();   //创建http对象
let postOptions: http.HttpRequestOptions = {    //设置请求参数
  method: http.RequestMethod.POST,    //设置请求方法
  extraData: {               //设置请求体数据
    username: 'testUser',
    password: '000000'
  },
  expectDataType: http.HttpDataType.STRING,      //设置返回数据类型
  header: {                                  //设置请求头
    'Content-Type': 'application/json'
  },
  readTimeout: 60000,            //设置超时时间
  connectTimeout: 60000               //设置连接超时时间
}

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
        Button('login')
          .onClick(() => {
            httpRequest.request('localhost:8080/api/login',postOptions,(err: Error, data: http.HttpResponse) => {
              if (err) {
                console.log('error:' + err.message);
              } else {
                console.log('data:' + data.result);
                console.info('code:' + data.responseCode);
                console.info('type:' + JSON.stringify(data.resultType));
                console.info('header:' + JSON.stringify(data.header));

                //解析返回数据
                

              }
            })
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

各位大佬,data.result里面有status、message、token三个字段。怎么解析数据,并且把data.result中的token字段单独提取出来啊。感谢!


更多关于HarmonyOS 鸿蒙Next http怎么解析返回的数据,并提取其中的token的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html

8 回复

新建一个model 比如 message.ets文件 里面有status、message、token三个字段

头部引用过来

深色代码主题
复制
import { message } from '../model/message';

接收的时候。

深色代码主题
复制
let message = json.parse(data.result.toString()) as message;

message.token //就是你获取的了

然后你可以通过dataPreferences 存在本地

然后判断用户是否登录 别的语言比如C#,OC。基本上都差不多。。。

流程就是解析json转model模型,存储本地。请求接口带上token提交验证。

更多关于HarmonyOS 鸿蒙Next http怎么解析返回的数据,并提取其中的token的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


message.token 获取的值和上面一样也是undefined,这是什么原因

前面直接输出的data.result里面是登陆成功有token的

你把result的内容在 json里面验证一下 看是不是json有问题。我都是这样转换的。。。 除非你json有问题。

创建一个接口,如名叫resData,内容如下:
{
status:number,
message:string,
token:string
}
使用:
let res:resData=JSON.parse(data.result.toString())
这样就能取到了
let token=res.token

01-08 09:02:57.093 22224-13520 A0c0d0/JSAPP I data:{“status”:1,“message”:“登陆成功!”,“token”:“Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTcsInVzZXJuYW1lIjoidGVzdFVzZXIiLCJwYXNzd29yZCI6IiIsIm5pY2tuYW1lIjoi5rWL6K-V55So5oi3IiwiZW1haWwiOiIzMzExMTExMTExMUBxcS5jb20iLCJ1c2VyX3BpYyI6IiIsImlhdCI6MTczNjI5ODE3NywiZXhwIjoxNzM2MzAxNzc3fQ.p7qMeknVaJ71M_MSGtLSouC0r1vK0VL3FQqKUtMLTnY”} 01-08 09:02:57.093 22224-13520 A0c0d0/JSAPP I code:200 01-08 09:02:57.093 22224-13520 A0c0d0/JSAPP W The json.parse interface in the Previewer is a mocked implementation and may behave differently than on a real device. 01-08 09:02:57.093 22224-13520 A0c0d0/JSAPP I token:undefined

为什么这里获取的token值为undefined

前面直接输出的data.result里面是登陆成功有token的

在HarmonyOS鸿蒙Next中,解析HTTP返回的数据并提取其中的token,通常可以使用系统提供的网络请求库(如ArkUI中的fetch API)以及JSON解析库(如JSON.parse)。

具体步骤如下:

  1. 发送HTTP请求: 使用fetch API发送HTTP请求,获取服务器返回的响应。

  2. 获取响应内容: 使用.responseText().json()方法获取响应内容。若响应为JSON格式,推荐使用.json()方法,该方法会自动将JSON字符串解析为JavaScript对象。

  3. 提取token: 从解析后的JavaScript对象中,通过键名访问并提取token。例如,如果token在响应对象的data属性中,且键名为token,则可通过responseData.data.token获取。

示例代码(假设使用ArkUI):

fetch('your-api-url')
  .then(response => response.json())
  .then(data => {
    let token = data.token; // 假设token在data对象中
    console.log(token);
  })
  .catch(error => {
    console.error('Error:', error);
  });

上述代码展示了如何在HarmonyOS鸿蒙Next中解析HTTP返回的JSON数据并提取token。如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!