Flutter:HttpClient post contentLength -- 异常

boe*_*edi 2 flutter

很奇怪...

为了将一些 JSON 数据发布到我的服务器,我将 contentLength 定义为 JSON 编码数据的长度,但随后我收到一个异常,提示“内容大小超过指定的 contentLength ”。相差1字节。

这是源代码:

Future<Map> ajaxPost(String serviceName, Map data) async {
  var responseBody = json.decode('{"data": "", "status": "NOK"}');
  try {
    var httpClient = new HttpClient();
    var uri = mid.serverHttps ? new Uri.https(mid.serverUrl, _serverApi + serviceName)
                              : new Uri.http(mid.serverUrl, _serverApi + serviceName);
    var request = await httpClient.postUrl(uri);
    var body = json.encode(data);

    request.headers
      ..add('X-mobile-uuid', await _getDeviceIdentity())
      ..add('X-mobile-token', await mid.getMobileToken());

    request.headers.contentLength = body.length;
    request.headers.set('Content-Type', 'application/json; charset=utf-8');
    request.write(body);

    var response = await request.close();
    if (response.statusCode == 200){
      responseBody = json.decode(await response.transform(utf8.decoder).join());

      //
      // If we receive a new token, let's save it
      //
      if (responseBody["status"] == "TOKEN"){
        await mid.setMobileToken(responseBody["data"]);

        // Let's change the status to "OK", to make it easier to handle
        responseBody["status"] = "OK";
      }
    }
  } catch(e){
    // An error was received
    throw new Exception("AJAX ERROR");
  }
  return responseBody;
}
Run Code Online (Sandbox Code Playgroud)

其他时候,它工作得很好......

我对这段代码做错了什么吗?

非常感谢您的帮助。

编辑解决方案

非常感谢您的帮助。简单的使用事实utf8.encode(json.encode(data))并没有完全发挥作用。所以,我转向http库,它现在就像一个魅力。代码更轻!

这是新版本的代码:

Future<Map> ajaxPut(String serviceName, Map data) async {
  var responseBody = json.decode('{"data": "", "status": "NOK"}');
  try {
    var response = await http.put(mid.urlBase + '/$_serverApi$serviceName',
        body: json.encode(data),
        headers: {
          'X-mobile-uuid': await _getDeviceIdentity(),
          'X-mobile-token': await mid.getMobileToken(),
          'Content-Type': 'application/json; charset=utf-8'
        });

    if (response.statusCode == 200) {
      responseBody = json.decode(response.body);

      //
      // If we receive a new token, let's save it
      //
      if (responseBody["status"] == "TOKEN") {
        await mid.setMobileToken(responseBody["data"]);

        // Let's change the status to "OK", to make it easier to handle
        responseBody["status"] = "OK";
      }
    }
  } catch (e) {
    // An error was received
    throw new Exception("AJAX ERROR");
  }
  return responseBody;
}
Run Code Online (Sandbox Code Playgroud)

Sdl*_*ion 6

我得到它与

\n

req.headers.contentLength = utf8.encode(body).length;

\n

来自Utf8Codec的间接提示其中指出

\n
\n

解码(列表 codeUnits,{ bool allowedMalformed })\xe2\x86\x92 字符串

\n

将 UTF-8 codeUnits(无符号 8 位整数列表)解码为相应的字符串。

\n
\n

这意味着utf8.encode()返回codeUnits实际上意味着List<uint8>.

\n

理论上,对字符串有效负载进行编码会返回一个列表,其长度是有效负载的长度(以字节为单位)。

\n

因此,使用httpClient方法始终测量有效负载的长度(以字节为单位),而不是可能不同的字符串的长度。

\n