Received GCM message displayed with garbled text

I have a Servlet deployed to the Google App Engine that plays the role of sending a broadcast message to GCM. Android clients will receive this broadcast message from GCM. The servlet extends the BaseServlet with the following snippet.

@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { //when receiving a gcm broadcast request, send message to GCM Builder mb = new Message.Builder(); mb.addData("message", "The message to send"); Message message = mb.build(); sender.sendNoRetry(message, regIds); ... } 

When the "message to send" is written in English, everything is in order. But if the “send message” is replaced with another language, such as Chinese, the Android client will receive a string of garbled text. On the Android client, I use a class that extends GCMBaseIntentService to work with GCM translation.

 @Override protected void onMessage(Context context, Intent intent) { String message = ""; message = intent.getStringExtra("message")!=null ? intent.getStringExtra("message") : ""; doNotify(message); } 

I tried to transcode the message, but it does not work.

 message = new String(message.getBytes("ISO-8859-1"), "UTF-8"); 

Any idea of ​​the problem? I need your help, thanks.

+4
source share
1 answer

Try URLEncoder

 mb.addData("message", URLEncoder.encode("世界","UTF-8"); 

another variant:

 mb.addData("message", new StringEntity("世界", "UTF-8"); 

After looking at the GCM source code: com.google.android.gcm.server.Sender, it uses HttpPost as json, and Java uses UTF-16 for internal use, before you publish it, you need to code it properly.
And, as the comment said, when decoding the String client

 String yourAwesomeUnicodeString=URLDecoder.decode(intent.getStringExtra("message"),"UTF-8"); 
+7
source

All Articles