46

I'm using this code to get scandinavian characters posted to php correctly.

Issue here is that StandardCharsets.UTF_8 is not supported before API 19

byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

DataOutputStream wr = new DataOutputStream( con.getOutputStream());
wr.write( postData );

Field requires API level 19 (Current min is 14): java.nio.charset.StandardCharsets#UTF_8

How should I do this with API lower than 19?

Kirill Feoktistov
  • 1,448
  • 24
  • 28
EspeH
  • 1,308
  • 2
  • 16
  • 34

1 Answers1

91

Use forName static method of Charset class:

byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));

List of standard charsets you can find in documentation.

Kirill Feoktistov
  • 1,448
  • 24
  • 28
  • 1
    With Android SDK 31, Charset seems to reference StandardCharsets and cause a crash in API lower than 19. Bummer. – faraday Dec 12 '21 at 19:31
  • @faraday Did you find any solution for that? I mean a way to use UTF-8 on SDK 31, but also lower than 19? – Joey Feb 04 '22 at 14:03
  • 1
    @Joey I tried different ways of working around it but despite not directly referencing Charset, there seems to be indirect connections to it inside the SDK. I couldn't succeed yet. – faraday Feb 05 '22 at 19:59