HarmonyOS鸿蒙Next中如何使用 http.HttpRequest 发送application/x-www-form-urlencoded请求数据?是否可以自动转换数据。

HarmonyOS鸿蒙Next中如何使用 http.HttpRequest 发送application/x-www-form-urlencoded请求数据?是否可以自动转换数据。 请问使用 http.HttpRequest 如何发送 application/x-www-form-urlencoded 请求数据? 是否可以自动转换数据。

3 回复

当’content-Type’为’application/x-www-form-urlencoded’时,请求提交的信息主体数据必须在key和value进行URL转码后(encodeURIComponent/encodeURI),按照键值对"key1=value1&key2=value2&key3=value3"的方式进行编码,该字段对应的类型通常为String。

文档说明:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-http-V5#httprequestoptions

当前’Content-Type’设置为’application/x-www-form-urlencoded’,需要手动设置extraData格式为key1=value1&key2=value2&key3=value3的方式,不会自动转换。

更多关于HarmonyOS鸿蒙Next中如何使用 http.HttpRequest 发送application/x-www-form-urlencoded请求数据?是否可以自动转换数据。的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,使用http.HttpRequest发送application/x-www-form-urlencoded请求数据时,可以通过设置headerbody来实现。首先,需要将请求头Content-Type设置为application/x-www-form-urlencoded。然后,将请求数据以键值对的形式拼接成字符串,并设置为body

示例代码如下:

import http from '@ohos.net.http';

let httpRequest = http.createHttp();
let url = 'https://example.com/api';
let params = {
    key1: 'value1',
    key2: 'value2'
};

let body = Object.keys(params).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`).join('&');

let options = {
    method: http.RequestMethod.POST,
    header: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    extraData: body
};

httpRequest.request(url, options, (err, data) => {
    if (err) {
        console.error(`Request failed, code is ${err.code}, message is ${err.message}`);
    } else {
        console.info('Request successful:', data.result);
    }
});

鸿蒙Next的http.HttpRequest不会自动将对象转换为x-www-form-urlencoded格式,需要手动拼接并编码键值对。

在HarmonyOS鸿蒙Next中,使用http.HttpRequest发送application/x-www-form-urlencoded请求数据时,可以通过设置headerbody来实现。数据不会自动转换,需要手动将对象转换为x-www-form-urlencoded格式的字符串。示例代码如下:

import http from '@ohos.net.http';

let httpRequest = http.createHttp();
let url = 'https://example.com/api';
let params = { key1: 'value1', key2: 'value2' };
let body = Object.keys(params).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`).join('&');

httpRequest.request(url, {
  method: http.RequestMethod.POST,
  header: { 'Content-Type': 'application/x-www-form-urlencoded' },
  extraData: body
}, (err, data) => {
  if (err) {
    console.error('Request failed', err);
  } else {
    console.log('Response:', data.result);
  }
});

此代码展示了如何手动构建URL编码的请求体并发送POST请求。

回到顶部