Google GCM : Avoid weird characters in notifications


When using Google GCM, we have to be sure that the message is properly encoded, in case of non-latin characters, when reaching to the devices to avoid weird characters when is show.gcm-logo-e1357123459595

To achieve this, the first approach could be to do an URL-Encode the message and decode it when get from the notification but in case of iOS, if the application is not in foreground, the notification goes directly to the system and there we can not do a URL-Decode so, the correct way, when using GCM through HTTP, is to encode properly the JSON GCM request in UTF-8 before making the POST to GCM. As a brief, with Apache HTTP:

  • Add “http.protocol.content-charset” with the value “UTF-8” to the POST request.
  • Set the JSON data through an StringEntity with “UTF-8” character encoding set.


Here i put an example of GCM JSON for a HTTP POST:

		"title":"Notification title",
		"message":"Hi iOS and Android",
		"title":"Notification title",
		"body":"Hi iOS and Android",

and here the request, POST, with Apache HTTP client of the GCM JSON:

//Create the HttpClient and Configure
DefaultHttpClient httpclient = new DefaultHttpClient();
// The time it takes to open TCP connection.
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_DEFAULT_TIMEOUT);
// Timeout when server does not send data.
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, CONNECTION_DEFAULT_DATA_RECEIVAL_TIMEOUT);
// Some tuning that is not required for bit tests.
//httpclient.getParams().setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
httpclient.getParams().setParameter(CoreConnectionPNames.TCP_NODELAY, true);
//Set the header of the content to UTF-8
httpMethod.setHeader(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");//Set the content through an StringEntity specifying the "UTF-8".
StringEntity se = new StringEntity(jsonData, "UTF-8");((HttpPost)httpMethod).setEntity(se); 
HttpResponse response = httpclient.execute(httpMethod);



Give it a try if you are with such character issues.



Javier González Serrano. EnjoYing CodiNg New IdeAs

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.