往期鸿蒙全套实战文章必看:(附带鸿蒙全栈学习资料)


http请求如何以表单形式进行传输

在HTTP协议消息头中,使用Content-Type来表示媒体类型信息,设置该参数值为“application/x-www-form-urlencoded”。

import { http } from '@kit.NetworkKit';

let options: http.HttpRequestOptions = {
  method: http.RequestMethod.GET,
  extraData: 'send message',
  header: { 'Content-Type': 'application/x-www-form-urlencoded' },
  readTimeout: 50000,
  connectTimeout: 50000
}

  extraData表示发送请求的数据,目前支持string、Object和ArrayBuffer三种类型。

let httpRequest = http.createHttp();
let data = "user=Query&passowrd=Admin123";
httpRequest.request(
  // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定   "https:xxx-xxx-xxx",  
  {
    method: http.RequestMethod.POST,
    // 可选,默认为http.RequestMethod.GET   // 开发者根据自身业务需要添加header字段   
    header: { 'Content-Type': 'application/x-www-form-urlencoded' }, // 当使用POST请求时此字段用于传递内容   
    extraData: data,
    connectTimeout: 60000, // 可选,默认为60000ms   
    readTimeout: 60000, // 可选,默认为60000ms   
  }, (err, data) => {
  if (!err) {
    // data.result为HTTP响应内容,可根据业务需要进行解析        
    console.info('Result:' + JSON.stringify(data.result));
    console.info('code:' +
    JSON.stringify(data.responseCode)); // data.header为HTTP响应头,可根据业务需要进行解析       
    console.info('header:' + JSON.stringify(data.header));
    console.info('cookies:' +
    JSON.stringify(data.cookies)); // 从api8开始   
  } else {
    console.info('error:' +
    JSON.stringify(err)); // 取消订阅HTTP响应头事件  
    httpRequest.off('headersReceive'); // 当该请求使用完毕时,调用destroy方法主动销毁。 
    httpRequest.destroy();
  }
})


​

更多推荐