Google GCM : Avoid weird characters in notifications

Hi,

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:

{
	"collapse_key":"collapse_key_value",
	"delay_while_idle":false,
	"data":{
		"title":"Notification title",
		"message":"Hi iOS and Android",
		"url":"url_address",
		"sound":"default"	
		},
	"notification":{
		"title":"Notification title",
		"body":"Hi iOS and Android",
		"sound":"default",
		"url":"url_adress"
	},
	"registration_ids":["registration_id"]
}

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.

 

bye!

Leave a Reply

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