How to encode cyrillic symbols in HTTP-requests in Java?
Asked Answered
I

4

5

Good time! My Adroid app executes HTTP request to the one of the API services of Google. Sure, it works, when the parameter of the request in english, but when I test my function with cyrillic - I get the 400-error. Seems to be, the problem is to encode the Win-1251 string to UTF-8 ?How it can be done in Java ?

Iminourea answered 3/9, 2011 at 19:15 Comment(0)
I
13

Try:

URLEncoder.encode(yourString, HTTP.UTF-8);
Isherwood answered 3/9, 2011 at 19:19 Comment(2)
Deprecatad( UTF-8Given
use URLEncoder.encode(yourString, java.nio.charset.StandardCharsets.UTF_8.toString())Wenda
K
10

You should use URLEncoder#encode() to encode request parameters.

String query = "name1=" + URLEncoder.encode(value1, "UTF-8")
            + "&name2=" + URLEncoder.encode(value2, "UTF-8")
            + "&name3=" + URLEncoder.encode(value3, "UTF-8");

String url = "http://example.com?" + query;
// ...

Note that parameter names should actually also be URL-encoded, however in this particular example, they are all valid already. Also note that when you're using Android's builtin HttpClient API, you don't need to do this.

Kenley answered 3/9, 2011 at 19:19 Comment(1)
Yeh, thanks for details, especially about Android's HttpClientIminourea
M
2

All String objects in Java are encoded as Unicode (UTF-16) and Unicode includes characters from the Windows-1251 character set.

For example, "Česká" is "\u010Cesk\u00E1".

If you want to send this string to other software using a different character set then you need to convert the string to bytes in that character set using class CharsetEncoder, or using class OutputStreamWriter and passing the Charset.

And if you receive a string from other software in a different character set then use class CharsetDecoder or InputStreamReader with the Charset to convert it to back Unicode.

Meretricious answered 3/9, 2011 at 19:36 Comment(0)
S
0

Update on depricated parameter:

import static java.nio.charset.StandardCharsets.UTF_8;

String pathEncoded = "";

try {

  pathEncoded = URLEncoder.encode(path, UTF_8.toString());

} catch (UnsupportedEncodingException e) {

  e.printStackTrace();
}
Spectrophotometer answered 30/9, 2019 at 7:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.