【问题标题】:HttpClient doesn't send request with json with russian charactersHttpClient 不使用带有俄语字符的 json 发送请求
【发布时间】:2018-03-08 22:45:01
【问题描述】:

我制作客户端应用程序并使用 HttpClient。它完美地发送和获取带有拉丁符号的 json,但是当我尝试使用俄语字母(具有相同的请求地址和服务器)发送 json 时,它不会向服务器发送任何请求。 代码如下:

  class RestApiClientBase {

  static String _server;
  static String _ssid;
  final HttpClient _client = new HttpClient();
  static const _codec = const JsonEncoder.withIndent(" ");

  RestApiClientBase() {
    _client.badCertificateCallback =
        (X509Certificate cert, String host, int port) => true; //for self-signed cert
  }

  void setServer(String serverNew) {
    _server = serverNew;
  }

  void setSsid(String ssidNew) {
    _ssid = ssidNew;
  }

  dynamic invokePost(String method, String data) async {
    return await _client.postUrl(Uri.parse(_server + method))
        .then((HttpClientRequest request) async {
      //print('11111111111111111111111');
      request.headers.contentType
      = new ContentType("application", "json", charset: "utf-8");
      //print('22222222222222222222222');
      request.contentLength = data.length;
      //print('33333333333333333333333');
      request.write(data);
      //print('44444444444444444444444');
      return await request.close();
    })
        .then((HttpClientResponse response) async {
      if (response.statusCode == 200) {
        return response
            .transform(UTF8.decoder)
            .single;
      } else {
        String errorJson = RestApiClientBase._codec.convert(
            {
              "status": "error",
              "message": "Error code: ${response.statusCode}"
            });
        return errorJson;
      }
    }).then((String answer) async {
      var json = JSON.decode(answer);
      rState.setRState(method, json["status"], json["message"]);
      return json;
    });
  }
}
class SecurityGroupClient extends RestApiClientBase {
  dynamic getSGroups() async {
    String json = RestApiClientBase._codec.convert(
        {"ssid": RestApiClientBase._ssid});
    return await invokePost("sgroup/list", json);
  }

  dynamic createSGroup(String name, String info) async {
    String json = RestApiClientBase._codec.convert(
        {"ssid": RestApiClientBase._ssid, "name": name, "info": info});
    print(json);
    return await invokePost("sgroup/create", json);
  }
}

我收到所有消息 (111,222,333,444),但我没有收到任何其他消息。 下面是json的例子:

{
"ssid": "6a3b1d12-cd4d-4962-ae06-34d36e31ac7e",
"name": "Тестовая группа на русском",
“信息”:“тест”
} 服务器使用 https。

【问题讨论】:

    标签: json httpclient flutter


    【解决方案1】:

    这是因为内容长度错误。默认情况下,内容是 UTF8 编码的。所以实际上数据长度!=字符串长度。如果你运行控制台应用程序,它会抛出一个异常

    内容大小超过了指定的 contentLength。 69 字节写入而 预计 38。

    所以获得编码长度的最佳解决方案是:

    request.contentLength = UTF8.encode(data).length; 
    

    【讨论】:

      猜你喜欢
      • 2015-03-22
      • 1970-01-01
      • 2015-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多