Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode cyrillic symbols in HTTP-requests in Java?

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 ?

like image 958
Eugene Shmorgun Avatar asked Sep 03 '11 19:09

Eugene Shmorgun


2 Answers

Try:

URLEncoder.encode(yourString, HTTP.UTF-8);
like image 149
Nikola Despotoski Avatar answered Sep 17 '22 12:09

Nikola Despotoski


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.

like image 20
BalusC Avatar answered Sep 16 '22 12:09

BalusC