8

I am currently doing web development with dart. Implemented service with mockclient. However, the following error occurs. The implementation code below is an in memory web api service that inherits mockClient. The code that calls client.send () and returns the result.

test_value is the result of json.encode (data).

var test_value = '{"id": 1, "type": "Appetizer", "name": "한글"}';

     return Response (test_value, 200, headers: {'content-type': 'application / json'});

ERROR

Invalid argument(s): String contains invalid characters.
dart:convert                                           Latin1Codec.encode
package:http/src/response.dart 36:49                   new Response
package:basil/common/mock_rest/mock_recipe.dart 40:12  MockRecipe._handler

If you put an English string in the name of the above implementation code, there is no error. Why do I get an error when I insert a character other than English?

Please let me know if you know!

A dart programmer struggling alone in Korea

superpeace
  • 85
  • 1
  • 3

1 Answers1

19

The Response class uses Latin-1 encoding for the body unless something else is specified. This is not documented clearly on the constructor itself, but the documentation on the body getter does suggest this.

Try setting the charset/encoding in the header, e.g., as:

return Response(test_value, 200, headers: {
    HttpHeaders.contentTypeHeader: 'application/json; charset=utf-8'
});
lrn
  • 64,680
  • 7
  • 105
  • 121
  • I have read the source code. The key is `content-type` now. Check this: https://github.com/dart-lang/http/blob/19eed19bc393ca9618896de3f00608238a6010dc/lib/src/response.dart#L83 – Daniel Wei Apr 05 '19 at 19:17
  • That is what the code says. HTTP headers are case insensitive, so both `"Content-Type"` and `"content-type"` should work. The latter is likely more efficient because the key is mapped to lower case by the code before comparison. Or, you can just use the constant `HttpHeaders.contentTypeHeader`. I'll change the answer to do that – lrn Apr 08 '19 at 13:58