HarmonyOS 鸿蒙Next 网络请求application/x-www-form-urlencoded; charset=utf-8形式传递参数,有代码示例吗

发布于 1周前 作者 yibo5220 来自 鸿蒙OS

HarmonyOS 鸿蒙Next 网络请求application/x-www-form-urlencoded; charset=utf-8形式传递参数,有代码示例吗 请问一下网络请求application/x-www-form-urlencoded; charset=utf-8形式,传递参数,有代码示例吗

2 回复

/**

  • 网络请求配置 */ import { HashMap } from ‘@kit.ArkTS’;

export interface RequestOptions {

//请求地址 url?: string;

//请求类型,post、get等 method?: RequestMethod;

//请求参数 queryParams ?: Record<string, string>;

//自定义请求头 header?: Object;

//是否显示loading showLoading? : boolean

//加载完成是否关闭loading closeLoading? : boolean

}

export enum RequestMethod { OPTIONS = “OPTIONS”, GET = “GET”, HEAD = “HEAD”, POST = “POST”, PUT = “PUT”, DELETE = “DELETE”, TRACE = “TRACE”, CONNECT = “CONNECT” }

import http from ‘@ohos.net.http’; import { RequestOptions } from ‘./RequestOption’; import { BusinessError } from ‘@kit.BasicServicesKit’; import { CommonUtil } from ‘…/utils/CommonUtil’; import { url } from ‘@kit.ArkTS’; import { CommonConstants } from ‘…/constans/CommonConstants’;

/**

  • Http请求器 / export class HttpCore { /*
    • 发送请求 */ request<T>(requestOption: RequestOptions): Promise<T> { return new Promise<T>((resolve, reject) => { this.sendRequest(requestOption) .then((response) => { if (typeof response.result !== ‘string’) { reject(new Error(‘Invalid data type’));

       } else {
         let bean: T = JSON.parse(response.result);
         if (bean) {
           resolve(bean);
         } else {
           reject(new Error('Invalid data type,JSON to T failed'));
         }
      
       }
      

      }) .catch((error: BusinessError) => { reject(JSON.stringify(error)); }); }); }

private sendRequest(requestOption: RequestOptions): Promise<http.HttpResponse> {

// 每一个httpRequest对应一个HTTP请求任务,不可复用
let httpRequest = http.createHttp();

let resolveFunction: Function
let rejectFunction: Function
const resultPromise = new Promise<http.HttpResponse>((resolve, reject) => {
  resolveFunction = resolve;
  rejectFunction = reject;
});

if (CommonUtil.isStringEmpty(requestOption.url)) {
  return Promise.reject(new Error('url不能为空'));
}

let promise = httpRequest.request(CommonConstants.BASE_URL + requestOption.url, {
  method: requestOption.method,
  header: requestOption.header,
  extraData: new url.URLParams(requestOption.queryParams).toString(), // 当使用POST请求时此字段用于传递内容
  expectDataType: http.HttpDataType.STRING // 可选,指定返回数据的类型
});

promise.then((response) => {

  console.info('Result:' + response.result);
  console.info('code:' + response.responseCode);
  console.info('header:' + JSON.stringify(response.header));


  if (http.ResponseCode.OK !== response.responseCode) {
    throw new Error('http responseCode !=200');
  }
  resolveFunction(response);

}).catch((err: BusinessError) => {
  rejectFunction(err);
}).finally(() => {
  // 当该请求使用完毕时,调用destroy方法主动销毁。
  httpRequest.destroy();
})
return resultPromise;

}

// private appendQueryParams(url?: string, queryParams?: Record<string, string>): string { // // // todo 使用将参数拼接到url上 // return url; // } }

export const httpCore = new HttpCore();

import { httpCore as HttpCore } from ‘./HttpCore’; import { RequestOptions } from ‘./RequestOption’;

/**

  • 对外管理器 */ export class HttpManager { private static mInstance: HttpManager = new HttpManager();

// 防止实例化 private constructor() { }

static getInstance(): HttpManager { return HttpManager.mInstance; }

request<T>(option: RequestOptions): Promise<T> { return HttpCore.request(option); } }

最后 调用 let options : object = { method: RequestMethod.GET, header: { ‘Content-Type’: ‘application/x-www-form-urlencoded; charset=UTF-8’ } } as http.HttpRequestOptions;

HttpManager.getInstance().request<TestBean>(options)

更多关于HarmonyOS 鸿蒙Next 网络请求application/x-www-form-urlencoded; charset=utf-8形式传递参数,有代码示例吗的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS(鸿蒙)系统中进行网络请求,并以application/x-www-form-urlencoded; charset=utf-8形式传递参数,可以使用ArkUI框架中的Fetch API。以下是一个简单的代码示例,展示了如何进行此类网络请求:

// 引入Fetch API模块(在ArkUI框架中通常已内置)

// 定义网络请求的URL
const url = 'https://example.com/api';

// 定义要传递的参数
const params = {
    key1: 'value1',
    key2: 'value2'
};

// 将参数转换为URL编码的查询字符串
const queryString = Object.keys(params)
    .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(params[key]))
    .join('&');

// 发起网络请求
fetch(url, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
    },
    body: queryString
})
.then(response => response.json())
.then(data => {
    console.log('Response data:', data);
})
.catch(error => {
    console.error('Error:', error);
});

此代码示例展示了如何构造URL编码的查询字符串,并使用Fetch API发起POST请求。请确保将url替换为您的实际API端点,并根据需要调整params对象中的参数。

如果问题依旧没法解决请联系官网客服,官网地址是 https://www.itying.com/category-93-b0.html

回到顶部