Dart 什么鬼,原生组件 POST 数据失败,并且查不到相关信息

代码如下,只要向 HttpClientRequest 写入内容就会失败:

import 'package:PakParty/common/Log.dart';
import 'dart:io';
import 'dart:convert';

main() async {
  HttpClient httpClient = new HttpClient();
  //https://pakparty.allyworld.cn:8444/api/client/detail?aa=bb&cc=dd
  Uri uri = Uri(scheme: "https",
      host: "pakparty.allyworld.cn",
      port: 8444,
      path: '/api/client/detail',
      queryParameters: {"aa": "bb", "cc": "dd"});

  HttpClientRequest request = await httpClient.postUrl(uri);

  request.headers.add("user-agent", "test");
  request.add(utf8.encode("............."));
  request.contentLength = -1;

  HttpClientResponse response = await request.close();
  String responseBody = await response.transform(utf8.decoder).join();
  Log.i(responseBody);
  httpClient.close();
}

错误信息:

$ dart lib/test.dart
lib/test.dart: Warning: Interpreting this as package URI, 'package:PakParty/test.dart'.
Unhandled exception:
HttpException: HTTP headers are not mutable
#0      _HttpHeaders._checkMutable (dart:_http/http_headers.dart:450:20)
#1      _HttpHeaders.contentLength= (dart:_http/http_headers.dart:143:5)
#2      _HttpOutboundMessage.contentLength= (dart:_http/http_impl.dart:790:13)
#3      main (package:PakParty/test.dart:17:11)
<asynchronous suspension>
#4      _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:307:19)
#5      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:174:12)

按理说,默认的,简单的,不作死的写法不应该出错。根据错误提示 HTTP headers are not mutable 找不到相关内容。好几天了还没有突破,也没有看到别人的经验。

很多人推荐使用 pub 库里的组件,那原生的组件是做什么用的?

一亩三分地儿
讨论数量: 1
一亩三分地儿

放弃使用原生组件,凡人无法使用,改用 http。后来才发现在 https://pub.dev/ 中有作者是 dart.dev 和 flutter.dev 的组件,这应该是官方出品的,比较人性化的组件吧。

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!