鸿蒙 6.1 API 23 开发坑系列篇 7:@ohos.net.http HTTP 请求坑——HttpDataType 常量是 STRING 不是 STRING_TYPE + HttpRequest 是 interface 不能 new + http.createHttp() 造实例根因

本文是「鸿蒙 6.1 API 23 开发坑系列」第 7 篇(非 UI 系第 1 篇)。本篇讲 @ohos.net.http namespace(API 6+,鸿蒙 6.1 API 23 基座)——HTTP 请求 HttpRequest + http.createHttp() + HttpDataType/RequestMethod enum + on/off 监听 + request/requestInStream 方法。鸿蒙坑根因:① HttpDataType enum 常量是 STRING(不是 STRING_TYPE,跟字面量 "string" 对应,enum 值是数字 0);② HttpRequest 是 interface 不能 newnew http.HttpRequest() 编译错 Cannot use 'new' with an interface),必须用 http.createHttp() 工厂函数造实例;③ on('headersReceive')/off('headersReceive', callback) 监听响应头不是 addEventListener/removeEventListener;④ HttpRequestOptions.headerRecord<string, string> 不是 Headers 对象(不能 new Headers());⑤ RequestMethod enum 常量 GET/POST/PUT/DELETE(不是字符串 'GET')。

一、开篇:鸿蒙 http 不是 fetch,是「http.createHttp() 工厂造 HttpRequest 实例 + on/off 监听」

你写前端时,HTTP 请求用 fetch(Promise 链,Headers 对象,addEventListener 监听):

// React fetch:Promise 链,Headers 对象,addEventListener 监听
const headers = new Headers()  // ✅ 前端 Headers 对象可以 new
headers.append('Content-Type', 'application/json')
const res = await fetch('https://api.example.com/data', {
  method: 'GET',  // ✅ 前端 method 是字符串 'GET'
  headers
})
const data = await res.json()  // ✅ 前端 fetch 返回 Promise,.json() 取 body

你写鸿蒙 ArkTS 时,HTTP 请求用 http.createHttp() 工厂造 HttpRequest 实例HttpRequest 是 interface 不能 newon/off 监听,request 方法带回调):

// ArkTS http.createHttp():工厂造 HttpRequest 实例,on/off 监听,request 方法带回调
import http from '@ohos.net.http'  // ✅ default import(http 是 namespace)

const httpRequest: http.HttpRequest = http.createHttp()  // ✅ 工厂函数造实例(不是 new http.HttpRequest())
const options: http.HttpRequestOptions = {
  method: http.RequestMethod.GET,  // ✅ RequestMethod enum 常量 GET(不是字符串 'GET')
  header: { 'Content-Type': 'application/json' },  // ✅ header 是 Record<string, string> 不是 Headers 对象
  expectDataType: http.HttpDataType.STRING  // ✅ HttpDataType 常量 STRING(不是 STRING_TYPE)
}
httpRequest.request('https://api.example.com/data', options, (err, data) => {  // ✅ request 带回调不是 Promise
  if (!err) {
    console.info('response: ' + data.result)  // ✅ data.result 是响应体(STRING 类型返回 string)
  }
})
// 鸿蒙坑根因:HttpDataType STRING 不是 STRING_TYPE,HttpRequest interface 不能 new 用 http.createHttp()

fetch vs 鸿蒙 http 的区别:前端把 HTTP 请求当浏览器 API(fetch(url, init) 返回 Promise<Response>Headers 对象可以 newmethod 是字符串 'GET'addEventListener 监听),ArkTS 把 HTTP 请求当 ArkUI 命名空间工厂(http.createHttp()HttpRequest 实例,HttpRequest 是 interface 不能 newmethodRequestMethod enum 常量不是字符串,headerRecord<string, string> 不是 Headers 对象,on/off 监听不是 addEventListener)。根因不是浏览器 API 是 ArkTS 命名空间工厂——鸿蒙 HttpRequest 是 interface 不能 new,必须 http.createHttp() 工厂造实例;HttpDataType enum 常量是 STRING 不是 STRING_TYPE(跟字面量 "string" 对应,enum 值是数字 0)。

二、根因:鸿蒙 @ohos.net.http 的五个绑定机制

鸿蒙 @ohos.net.http namespace(API 6+)核心导出 http.createHttp() 工厂函数 + HttpRequest interface + HttpDataType/RequestMethod enum + HttpRequestOptions/HttpResponse 类型。绑定机制来自五重根因。

机制 1:HttpDataType enum 常量是 STRING 不是 STRING_TYPE——跟字面量“string“对应,enum 值是数字 0

鸿蒙坑根因:HttpDataType enum 常量是 STRING(不是 STRING_TYPE),跟字面量 "string" 对应,enum 值是数字 0

// ❌ 鸿蒙坑:HttpDataType 常量是 STRING 不是 STRING_TYPE(STRING_TYPE 不存在编译错)
import http from '@ohos.net.http'

// ❌ STRING_TYPE 常量不存在(编译错 has no exported member 'STRING_TYPE')
const badType: http.HttpDataType = http.HttpDataType.STRING_TYPE  // ❌ STRING_TYPE 不存在

// ✅ 正确用法:HttpDataType.STRING 常量(跟字面量"string"对应,enum 值是数字 0)
const dataType: http.HttpDataType = http.HttpDataType.STRING  // ✅ 常量真名 STRING 不是 STRING_TYPE
console.info(`STRING=${dataType}`)  // ✅ STRING=0(enum 值是数字 0)

// ✅ HttpDataType enum 三个常量:STRING=0 / ARRAY_BUFFER=1 / OBJECT=2
const strType: http.HttpDataType = http.HttpDataType.STRING       // ✅ STRING=0(字符串)
const binType: http.HttpDataType = http.HttpDataType.ARRAY_BUFFER // ✅ ARRAY_BUFFER=1(ArrayBuffer)
const objType: http.HttpDataType = http.HttpDataType.OBJECT       // ✅ OBJECT=2(Object)
// 鸿蒙坑根因:HttpDataType 常量是 STRING 不是 STRING_TYPE,跟字面量"string"对应,enum 值是数字 0

HttpDataType 常量名坑根因:鸿蒙 HttpDataType enum 的三个常量是 STRING=0(字符串类型)、ARRAY_BUFFER=1(ArrayBuffer 二进制类型)、OBJECT=2(Object 对象类型)。鸿蒙坑:前端 fetch 的 responseType 是字符串 'string'/'arraybuffer'/'json',鸿蒙 HttpDataType 是 enum 常量不是字符串,且常量真名是 STRING(不是 STRING_TYPE)——STRING_TYPE 是其他库(如 @ohos.buffer)的命名风格,鸿蒙 @ohos.net.httpHttpDataTypeSTRING 跟字面量 "string" 对应(去掉 _TYPE 后缀),enum 值是数字 0 不是字符串。React responseType: 'string' 是字符串,鸿蒙 expectDataType: http.HttpDataType.STRING 是 enum 常量。

机制 2:HttpRequest 是 interface 不能 new——用 http.createHttp() 工厂函数造实例

鸿蒙坑根因:HttpRequest 是 interface 不能 new,必须用 http.createHttp() 工厂函数造实例:

// ❌ 鸿蒙坑:HttpRequest 是 interface 不能 new(new http.HttpRequest() 编译错)
import http from '@ohos.net.http'

// ❌ HttpRequest 是 interface 不能 new(编译错:Cannot use 'new' with an interface)
const badReq: http.HttpRequest = new http.HttpRequest()  // ❌ interface 不能 new

// ✅ 正确用法:http.createHttp() 工厂函数造 HttpRequest 实例
const httpRequest: http.HttpRequest = http.createHttp()  // ✅ 工厂函数造实例(不是 new)
// 鸿蒙坑根因:HttpRequest 是 interface 不能 new,必须 http.createHttp() 工厂函数造实例

HttpRequest interface 坑根因:鸿蒙 @ohos.net.http.d.tsHttpRequest 声明是 export interface HttpRequest { ... }(interface 不是 class),interface 没有构造函数不能 new鸿蒙坑new http.HttpRequest() 触发 Cannot use 'new' with an interface 编译错(ArkTS 严格模式 interface 不能实例化)——必须用 http.createHttp() 工厂函数造实例(工厂函数内部走 native 造实例,跟 new 不同)。前端 fetch 是全局函数不需要造实例,XMLHttpRequest 是 class 可以 new XMLHttpRequest(),鸿蒙 HttpRequest 是 interface 不能 new——必须 http.createHttp() 工厂。

机制 3:on(‘headersReceive’)/off 监听响应头——不是 addEventListener/removeEventListener

鸿蒙坑根因:on('headersReceive')/off('headersReceive', callback) 监听响应头,不是 addEventListener/removeEventListener

// ❌ 鸿蒙坑:on/off 监听不是 addEventListener/removeEventListener
import http from '@ohos.net.http'

const httpRequest: http.HttpRequest = http.createHttp()

// ❌ addEventListener/removeEventListener 不存在(HttpRequest interface 没有这两个方法)
// httpRequest.addEventListener('headersReceive', callback)  // ❌ addEventListener 不存在
// httpRequest.removeEventListener('headersReceive', callback)  // ❌ removeEventListener 不存在

// ✅ 正确用法:on('headersReceive', callback)/off('headersReceive', callback) 监听响应头
const headersCallback = (data: Object) => {
  console.info('headersReceive: ' + JSON.stringify(data))
}
httpRequest.on('headersReceive', headersCallback)  // ✅ on 监听响应头(不是 addEventListener)
httpRequest.off('headersReceive', headersCallback)  // ✅ off 取消监听(callback 传同一个引用)
// 鸿蒙坑根因:on/off 监听不是 addEventListener/removeEventListener,off callback 传同一个引用

on/off 监听坑根因:鸿蒙 HttpRequest interface 的监听方法是 on(type: string, callback: AsyncCallback<Object>): voidoff(type: string, callback?: AsyncCallback<Object>): void(跟篇 5 uiObserver.on/off 同构),不是前端的 addEventListener/removeEventListener鸿蒙坑HttpRequest interface 没有 addEventListener/removeEventListener 方法(编译错 Property does not exist)——必须用 on/off,且 off 的 callback 必须传同一个引用(不是匿名函数,匿名函数每次创建新引用无法匹配取消),不传 callback 则取消该 type 所有监听。前端 XMLHttpRequest.addEventListener('load', cb) 是 DOM 方法,鸿蒙 httpRequest.on('headersReceive', cb) 是 namespace �风格方法。

机制 4:HttpRequestOptions.header 是 Record<string, string> 不是 Headers 对象

鸿蒙坑根因:HttpRequestOptions.headerRecord<string, string> 不是 Headers 对象(不能 new Headers()):

// ❌ 鸿蒙坑:header 是 Record<string, string> 不是 Headers 对象(不能 new Headers())
import http from '@ohos.net.http'

// ❌ Headers 对象不存在(@ohos.net.http 没有 Headers 类型,new Headers() 编译错)
const badHeaders = new Headers()  // ❌ Headers 类型不存在(@ohos.net.http 没导出)
const badOptions: http.HttpRequestOptions = {
  method: http.RequestMethod.GET,
  header: badHeaders  // ❌ header 不是 Headers 对象是 Record<string, string>
}

// ✅ 正确用法:header 是 Record<string, string>(对象字面量,键值都是 string)
const options: http.HttpRequestOptions = {
  method: http.RequestMethod.GET,
  header: { 'Content-Type': 'application/json', 'Authorization': 'Bearer xxx' }  // ✅ Record<string, string>
}
// 鸿蒙坑根因:header 是 Record<string, string> 不是 Headers 对象,不能用 new Headers()

header 类型坑根因:鸿蒙 HttpRequestOptions.header 的类型是 Record<string, string>(对象字面量,键和值都是 string),不是前端的 Headers 对象。鸿蒙坑:前端 fetchheadersHeaders 对象(new Headers() 可以造,headers.append(key, value) 添加),鸿蒙 @ohos.net.http 没有 Headers 类型,header 直接是 Record<string, string> 对象字面量({ 'Content-Type': 'application/json' })——new Headers() 编译错 Cannot find name 'Headers'(鸿蒙没导出 Headers 类型)。前端 Headers 对象有 append/delete/get 方法,鸿蒙 Record<string, string> 是普通对象没方法,直接赋值。

机制 5:RequestMethod enum 常量 GET/POST/PUT/DELETE——不是字符串“GET“

鸿蒙坑根因:RequestMethod enum 常量 GET/POST/PUT/DELETE/HEAD/OPTIONS/CONNECT,不是字符串 'GET'

// ❌ 鸿蒙坑:method 是 RequestMethod enum 常量不是字符串'GET'
import http from '@ohos.net.http'

// ❌ method 传字符串'GET'编译错(RequestMethod enum 不是 string)
const badOptions: http.HttpRequestOptions = {
  method: 'GET',  // ❌ method 类型是 RequestMethod enum 不是 string
  header: { 'Content-Type': 'application/json' }
}

// ✅ 正确用法:method 传 RequestMethod enum 常量 GET/POST/PUT/DELETE
const options: http.HttpRequestOptions = {
  method: http.RequestMethod.GET,  // ✅ RequestMethod enum 常量 GET(不是字符串'GET')
  header: { 'Content-Type': 'application/json' }
}
// ✅ RequestMethod enum 常量:GET=0 / POST=1 / PUT=2 / DELETE=3 / HEAD=4 / OPTIONS=5 / CONNECT=6
const postOpt: http.HttpRequestOptions = { method: http.RequestMethod.POST }  // ✅ POST=1
const putOpt: http.HttpRequestOptions = { method: http.RequestMethod.PUT }    // ✅ PUT=2
const delOpt: http.HttpRequestOptions = { method: http.RequestMethod.DELETE } // ✅ DELETE=3
// 鸿蒙坑根因:method 是 RequestMethod enum 常量不是字符串'GET',enum 值是数字 0~6

RequestMethod enum 坑根因:鸿蒙 RequestMethod enum 的常量是 GET=0/POST=1/PUT=2/DELETE=3/HEAD=4/OPTIONS=5/CONNECT=6,跟前端 fetch 的 method: 'GET' 字符串不同。鸿蒙坑:前端 fetchmethod 是字符串 'GET'/'POST',鸿蒙 HttpRequestOptions.method 的类型是 RequestMethod enum 不是 string——传字符串 'GET' 触发 Type 'string' is not assignable to type 'RequestMethod' 编译错,必须传 http.RequestMethod.GET enum 常量(enum 值是数字 0 不是字符串)。React method: 'GET' 是字符串,鸿蒙 method: http.RequestMethod.GET 是 enum 常量。

三、真机配图:鸿蒙 @ohos.net.http HTTP 请求坑——HttpDataType STRING + HttpRequest interface + http.createHttp()

http 初始态 HttpDataType STRING 常量态 HttpRequest interface 不能 new 态 on/off headersReceive 监听态 requestOptions dataType+header 态

真机配图展示鸿蒙 @ohos.net.http HTTP 请求坑:

  • 初始态:鸿蒙 6.1 @ohos.net.http HTTP 请求坑标题,4 个验证按钮(① HttpDataType STRING 常量 / ② HttpRequest interface 不能 new / ③ on/off headersReceive 监听 / ④ requestOptions dataType+header),请求状态(requestStatus 未请求 + responseType 未设 + HttpDataType 值未读),要点说明 7 条
  • HttpDataType STRING 常量态:点击「① 验证 HttpDataType STRING 常量」按钮,显示「✅ HttpDataType.STRING 常量验证:真名 STRING 不是 STRING_TYPE(值=0)」+ HttpDataType 值 STRING=0——HttpDataType 常量真名 STRING 验证
  • HttpRequest interface 不能 new 态:点击「② 验证 HttpRequest interface 不能 new」按钮,显示「✅ http.createHttp() 造 HttpRequest 实例验证:interface 不能 new,用工厂函数」——HttpRequest interface 不能 new + http.createHttp() 工厂验证
  • on/off headersReceive 监听态:点击「③ 验证 on/off headersReceive 监听」按钮,显示「✅ on(“headersReceive”)/off 监听验证:on 不是 addEventListener,off 不是 removeEventListener」——on/off 监听不是 addEventListener/removeEventListener 验证
  • requestOptions dataType+header 态:点击「④ 验证 requestOptions dataType + header」按钮,显示「✅ HttpRequestOptions 验证:method RequestMethod.GET + expectDataType HttpDataType.STRING + header Record」——requestOptions enum 常量 + header Record 验证

四、真解法:鸿蒙 @ohos.net.http 的四个场景

场景 1:http.createHttp() 造 HttpRequest + request GET 请求——90% 场景首选

基础 GET 请求用 http.createHttp() 造实例 + request(url, options, callback) 方法:

// ✅ 场景 1:http.createHttp() 造 HttpRequest + request GET 请求(API 6,90% 场景首选)
import http from '@ohos.net.http'  // ✅ default import(http 是 namespace)

@Entry
@Component
struct Index {
  @State responseData: string = '(未请求)'
  private httpRequest: http.HttpRequest | null = null  // ✅ 持引用避免析构

  aboutToDisappear() {
    this.httpRequest?.destroy()  // ✅ destroy() 主动销毁避免内存泄漏
    this.httpRequest = null
  }

  sendGetRequest() {
    // ✅ http.createHttp() 工厂造实例(不是 new http.HttpRequest(),interface 不能 new)
    this.httpRequest = http.createHttp()
    const options: http.HttpRequestOptions = {
      method: http.RequestMethod.GET,  // ✅ RequestMethod enum 常量 GET(不是字符串'GET')
      header: { 'Content-Type': 'application/json' },  // ✅ Record<string, string> 不是 Headers 对象
      expectDataType: http.HttpDataType.STRING,  // ✅ HttpDataType 常量 STRING(不是 STRING_TYPE)
      connectTimeout: 60000,
      readTimeout: 60000
    }
    // ✅ request(url, options, callback) 带回调不是 Promise
    this.httpRequest.request('https://api.example.com/data', options, (err, data) => {
      if (!err) {
        // ✅ data.result 是响应体(expectDataType=STRING 时 data.result 是 string)
        this.responseData = data.result as string  // ✅ STRING 类型 result 是 string
        console.info('statusCode: ' + data.responseCode)
      } else {
        console.info('error: ' + JSON.stringify(err))
      }
    })
  }

  build() { Column({ space: 8 }) { Text(this.responseData).fontSize(12) } }
}
// http.createHttp() + request GET:90% 场景首选,HttpDataType STRING + RequestMethod enum 常量

鸿蒙 @ohos.net.http API 真名坑import http from '@ohos.net.http'(default import,http 是 namespace);http.createHttp(): HttpRequest(工厂函数造 HttpRequest 实例,不是 new http.HttpRequest()——HttpRequest 是 interface 不能 new);http.HttpRequest.request(url: string, options: HttpRequestOptions, callback: AsyncCallback<HttpResponse>): void(带回调不是 Promise);http.HttpRequest.destroy(): void(主动销毁避免内存泄漏);http.HttpDataType enum 常量 STRING=0/ARRAY_BUFFER=1/OBJECT=2(不是 STRING_TYPE);http.RequestMethod enum 常量 GET=0/POST=1/PUT=2/DELETE=3(不是字符串);SysCap SystemCapability.Communication.NetStack@atomicservice 原子化服务;权限 ohos.permission.INTERNET(module.json5 里 requestPermission)。

场景 2:on(‘headersReceive’)/off 监听响应头 + request POST 带 body

POST 请求带 body + on('headersReceive') 监听响应头:

// ✅ 场景 2:on('headersReceive')/off 监听响应头 + request POST 带 body(API 6)
import http from '@ohos.net.http'

this.httpRequest = http.createHttp()

// ✅ on('headersReceive', callback) 监听响应头——不是 addEventListener
const headersCallback = (data: Object) => {
  console.info('响应头: ' + JSON.stringify(data))
}
this.httpRequest.on('headersReceive', headersCallback)  // ✅ on 监听响应头

const options: http.HttpRequestOptions = {
  method: http.RequestMethod.POST,  // ✅ RequestMethod.POST enum 常量
  header: { 'Content-Type': 'application/json' },
  extraData: JSON.stringify({ username: 'admin', password: 'xxx' }),  // ✅ extraData 是 POST body
  expectDataType: http.HttpDataType.STRING
}
this.httpRequest.request('https://api.example.com/login', options, (err, data) => {
  if (!err) {
    console.info('response: ' + data.result)
  }
})

// ✅ off('headersReceive', callback) 取消监听——callback 传同一个引用
this.httpRequest.off('headersReceive', headersCallback)  // ✅ off 取消监听(同引用)
// on/off headersReceive 监听 + POST extraData body:on 不是 addEventListener,off callback 同引用

鸿蒙 on/off + POST API 真名坑http.HttpRequest.on(type: string, callback: AsyncCallback<Object>): void(监听,type 支持 'headersReceive' 响应头/dataReceiveEnd' 数据接收结束/dataReceiveProgress' 数据接收进度);http.HttpRequest.off(type: string, callback?: AsyncCallback<Object>): void(取消监听,callback 可选不传取消所有);http.HttpRequestOptions.extraData: string | Object | ArrayBuffer(POST 请求体,GET 请求不用);鸿蒙坑:前端 XMLHttpRequest.addEventListener('load', cb) 是 DOM 方法,鸿蒙 httpRequest.on('headersReceive', cb) 是 namespace 风格方法;前端 POST body 用 body 字段,鸿蒙 POST body 用 extraData 字段(不是 body)。

场景 3:requestInStream 流式请求 + ARRAY_BUFFER 二进制响应

流式请求用 requestInStream + ARRAY_BUFFER 二进制响应类型:

// ✅ 场景 3:requestInStream 流式请求 + ARRAY_BUFFER 二进制响应(API 6)
import http from '@ohos.net.http'

this.httpRequest = http.createHttp()
const options: http.HttpRequestOptions = {
  method: http.RequestMethod.GET,
  header: { 'Content-Type': 'application/json' },
  expectDataType: http.HttpDataType.ARRAY_BUFFER  // ✅ ARRAY_BUFFER=1(不是 STRING)
}
// ✅ requestInStream 流式请求(回调多次触发,每次返回一段数据)
this.httpRequest.requestInStream('https://api.example.com/stream', options, (err, data) => {
  if (!err) {
    // ✅ expectDataType=ARRAY_BUFFER 时 data.result 是 ArrayBuffer
    const buffer: ArrayBuffer = data.result as ArrayBuffer  // ✅ ARRAY_BUFFER 类型 result 是 ArrayBuffer
    console.info('收到流数据: ' + buffer.byteLength + ' bytes')
  }
})
// requestInStream 流式 + ARRAY_BUFFER:expectDataType 用 ARRAY_BUFFER 常量不是 STRING

鸿蒙 requestInStream + ARRAY_BUFFER API 真名坑http.HttpRequest.requestInStream(url: string, options: HttpRequestOptions, callback: AsyncCallback<HttpResponse>): void(流式请求,回调多次触发每次返回一段数据,不是 request 一次性返回);expectDataType: http.HttpDataType.ARRAY_BUFFERdata.resultArrayBuffer(二进制数据,不是 string);鸿蒙坑:前端 fetch 流式用 ReadableStream + response.body.getReader(),鸿蒙 requestInStream 用回调多次触发;前端二进制用 response.arrayBuffer(),鸿蒙 expectDataType: ARRAY_BUFFER + data.result as ArrayBuffer

场景 4:destroy() 主动销毁 + usingCache 缓存 + priority 优先级

请求完 destroy() 主动销毁 + usingCache 缓存控制 + priority 优先级:

// ✅ 场景 4:destroy() 主动销毁 + usingCache 缓存 + priority 优先级(API 6)
import http from '@ohos.net.http'

this.httpRequest = http.createHttp()
const options: http.HttpRequestOptions = {
  method: http.RequestMethod.GET,
  header: { 'Content-Type': 'application/json' },
  expectDataType: http.HttpDataType.STRING,
  usingCache: true,  // ✅ usingCache=true 使用缓存(不是 cache: 'force-cache' 字符串)
  priority: 0,  // ✅ priority 数字优先级(0 最高,不是 'high'/'low' 字符串)
  connectTimeout: 60000,  // ✅ 连接超时毫秒
  readTimeout: 60000  // ✅ 读取超时毫秒
}
this.httpRequest.request('https://api.example.com/data', options, (err, data) => {
  if (!err) {
    console.info('response: ' + data.result)
  }
  // ✅ 请求完后调 destroy() 主动销毁(避免内存泄漏,跟 aboutToDisappear 里 destroy 不冲突)
  this.httpRequest?.destroy()
  this.httpRequest = null
})
// destroy + usingCache + priority:usingCache 是 boolean 不是字符串,priority 是数字不是字符串

鸿蒙 destroy + usingCache + priority API 真名坑http.HttpRequest.destroy(): void(主动销毁 HttpRequest 实例,避免内存泄漏,跟 aboutToDisappear 里 destroy 配合);HttpRequestOptions.usingCache: boolean(是否使用缓存,true/false 不是字符串 'force-cache'/'no-cache');HttpRequestOptions.priority: number(优先级,数字 0 最高,不是字符串 'high'/'low');HttpRequestOptions.connectTimeout: number/readTimeout: number(超时毫秒,不是 React 的 timeout: 5000);鸿蒙坑:前端 fetchcache: 'force-cache' 是字符串,鸿蒙 usingCache: true 是 boolean;前端 priority 不存在(fetch 没 priority),鸿蒙 priority: 0 是数字(0 最高优先级)。

五、一句话哲学

写鸿蒙 ArkTS 记住:http 不是 fetch 是「http.createHttp() 工厂造 HttpRequest 实例 + on/off 监听」——鸿蒙 6.1 API 23 @ohos.net.http namespace(API 6+,鸿蒙 6.1 API 23 基座,http.createHttp() 工厂函数 + HttpRequest interface + HttpDataType/RequestMethod enum + HttpRequestOptions/HttpResponse 类型,SysCap SystemCapability.Communication.NetStack,@atomicservice,权限 ohos.permission.INTERNET)。根因不是浏览器 API 是 ArkTS 命名空间工厂——HttpDataType enum 常量是 STRING 不是 STRING_TYPE(✅ http.HttpDataType.STRING=0/ARRAY_BUFFER=1/OBJECT=2,跟字面量 "string" 对应去掉 _TYPE 后缀,❌ STRING_TYPE 不存在编译错 has no exported member),HttpRequest 是 interface 不能 new(✅ http.createHttp() 工厂函数造实例,❌ new http.HttpRequest() 编译错 Cannot use 'new' with an interface,interface 没有构造函数),on/off 监听不是 addEventListener/removeEventListener(✅ httpRequest.on('headersReceive', cb)/off('headersReceive', cb),❌ addEventListener/removeEventListener 不存在编译错 Property does not existoff callback 必须传同一个引用不是匿名函数),HttpRequestOptions.headerRecord<string, string> 不是 Headers 对象(✅ { 'Content-Type': 'application/json' } 对象字面量,❌ new Headers() 编译错 Cannot find name 'Headers',鸿蒙没导出 Headers 类型),RequestMethod enum 常量不是字符串 'GET'(✅ http.RequestMethod.GET=0/POST=1/PUT=2/DELETE=3,❌ method: 'GET' 编译错 Type 'string' is not assignable to type 'RequestMethod'),request 方法带回调不是 Promise(✅ httpRequest.request(url, options, (err, data) => {}),❌ await httpRequest.request(url, options) 不返回 Promise),extraData 是 POST body 不是 body 字段(前端 fetch 用 body,鸿蒙用 extraData),expectDataType 指定响应类型(STRING 返回 string / ARRAY_BUFFER 返回 ArrayBuffer / OBJECT 返回 Object),destroy() 主动销毁避免内存泄漏(跟 aboutToDisappear 配合),usingCache 是 boolean 不是字符串(true/false 不是 'force-cache')。HttpDataType STRING 常量 + HttpRequest interface 不能 new + http.createHttp() 工厂 + on/off 监听 + header Record + RequestMethod enum 是鸿蒙 6.1 @ohos.net.http HTTP 请求坑核心!

能力系列回链

  • 鸿蒙 7.0 新特性篇 1~17(沉浸式毛玻璃/Component3D/智能体框架/方舟引擎/星盾安全/星河互联/空间音频/可变字体/游戏快启/分布式数据盾/LTPO 可变帧率/AI 文档识别/多形态服务窗口/AI 反诈/机密计算/空间计算/小艺全面进化)
  • 鸿蒙 6.1 API 23 开发坑系列篇 1「ArkUI.modifier 装饰器坑」——attributeModifier + AttributeModifier 状态化节点修改器
  • 鸿蒙 6.1 API 23 开发坑系列篇 2「arkui.componentSnapshot 组件截图坑」——get/getSync/createFromBuilder 返回 image.PixelMap 像素图
  • 鸿蒙 6.1 API 23 开发坑系列篇 3「arkui.node 节点坑」——NodeController abstract class makeNode override + BuilderNode WrappedBuilder
  • 鸿蒙 6.1 API 23 开发坑系列篇 4「arkui.UIContext UI 上下文坑」——runScopedTask 不是 runScopedOnUiThread + 11 个子管理器
  • 鸿蒙 6.1 API 23 开发坑系列篇 5「arkui.observer UI 观察器坑」——uiObserver namespace 真名不是 observer + on type string literal
  • 鸿蒙 6.1 API 23 开发坑系列篇 6「@ohos.animator 动画器坑」——import @kit.ArkUI 不是 @ohos.animator + onFrame 驼峰不是废弃 onframe + getUIContext().createAnimator 不是废弃 animator.create + 持引用 + aboutToDisappear cancel
  • 鸿蒙 6.1 API 23 开发坑系列篇 7「@ohos.net.http HTTP 请求坑」——HttpDataType 常量是 STRING 不是 STRING_TYPE + HttpRequest 是 interface 不能 new + http.createHttp() 工厂造实例 + on/off 监听不是 addEventListener + header Record 不是 Headers + RequestMethod enum 不是字符串(本文)
Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐