2017-09-27 27 views
1

我做客戶端應用程序,我使用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。

回答

2

這是因爲contentLength錯誤而發生的。默認情況下,內容是UTF8編碼的。所以實際上數據長度!=字符串長度。如果運行控制檯應用程序,它將拋出異常

內容大小超過指定的contentLength。 69個字節寫入,同時 預計38

所以最好的解決方案,使編碼長度爲:

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