简体   繁体   English

如何在Java中的HTTP请求中编码西里尔符号?

[英]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. 我的Adroid应用程序对Google的其中一个API服务执行HTTP请求。 Sure, it works, when the parameter of the request in english, but when I test my function with cyrillic - I get the 400-error. 当然,它的工作原理,当英语请求的参数,但当我用西里尔语测试我的功能 - 我得到400错误。 Seems to be, the problem is to encode the Win-1251 string to UTF-8 ?How it can be done in Java ? 似乎是,问题是将Win-1251字符串编码为UTF-8?如何在Java中完成?

尝试:

URLEncoder.encode(yourString, HTTP.UTF-8);

You should use URLEncoder#encode() to encode request parameters. 您应该使用URLEncoder#encode()来编码请求参数。

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. 请注意,参数名称实际上也应该是URL编码的,但在此特定示例中,它们都已经有效。 Also note that when you're using Android's builtin HttpClient API, you don't need to do this. 另请注意,当您使用Android的内置HttpClient API时,您不需要这样做。

All String objects in Java are encoded as Unicode (UTF-16) and Unicode includes characters from the Windows-1251 character set. Java中的所有String对象都编码为Unicode(UTF-16),Unicode包含来自Windows-1251字符集的字符。

For example, "Česká" is "\Česk\á". 例如,“Česká”是“\\ 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 . 如果要使用不同的字符集将此字符串发送到其他软件,则需要使用类CharsetEncoder将字符串转换为该字符集中的字节,或者使用类OutputStreamWriter并传递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. 如果从不同字符集中的其他软件接收字符串,则使用CharsetDecoder类或带有Charset InputStreamReader将其转换为Unicode。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM