HttpClient不发送请求与俄语字符的JSON

问题描述:

我做客户端应用程序,我使用HttpClient。它完美地发送和获取带有拉丁符号的json,但是当我尝试使用俄语字母(具有相同的请求地址和服务器)发送json时,它不会向服务器发送任何请求。 下面是代码:HttpClient不发送请求与俄语字符的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); 
    } 
} 

我得到的所有消息(111222333444),但我没有得到任何东西。 这里是JSON的例子:

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

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

内容大小超过指定的contentLength。 69个字节写入,同时 预计38

所以最好的解决方案,使编码长度为:

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