HTTPClient with UTF-8 but £ sign refuses to work

You must Login before you can answer or comment on any questions.

Hi all, hoping that someone can shed some light on this.

I am creating an HTTPClient call to load a JSON string. I set the content type and charset as follows:

theClient = Ti.Network.createHTTPClient();
theClient.open('GET', url);
theClient.setRequestHeader('Content-Type', 'application/json; charset=utf-8;');
theClient.send();

theClient.onload = function()  
{
    var theText = this.responseText;
    var theData = this.responseData;
}

This works fine for most calls but if the JSON contains any unusual characters, mainly the £ sign, the responseText just returns 'null'.

I can only assume that this is because it doesn't understand the character, maybe i'm not setting the charset correctly?

Any thoughts or longshots are welcome as i've tried everything i can think of :-)

As an aside...strangely the responseData returns an array of undefined variables corresponding to the number of characters in the expected response. For example if the response was simply 'hello£' the responseText would be null and the responseData would be an array of 6 variables all of which are undefined.

Thanks for any thoughts

Martyn

— asked 10 months ago by Martyn Joyce
2 Comments
  • How you testing the data returned? Have you tried using Fiddler2 or just inspecting the values in Ti Studio? Do you control the web service? Does it return 'hello' properly if you remove the £ character? Does the header returned also say it is a application/json; charset=utf-8;?

    — commented 10 months ago by Martin Grasso

  • Thanks for the comment, I have full control over the webservice and it returns the correct info in all cases, including the £ signs. The issue is that as this gets loaded into titanium it gets confused. The json works fine as this is a production app and the issue has been an oversight that has just occured.

    — commented 10 months ago by Martyn Joyce

1 Answer

Accepted Answer

Hi Martyn

You will need to encode any characters that fall outside the common ASCII table into Unicode equivalents. Consider pretty much anything in the top half of the ASCII table 128-255 as something you should encode.

Examples;

POUND = £ becomes \u00a3
HALF = ½ becomes \u00bd
QUARTER = ¼ becomes \u00bc
Used in your JSON or strings inside your code;
"\u00a310.50" = "£10.50"
Somewhat of a pain but once you build a filter the problem goes away. Just remember to use the Unicode hex values and not ASCII versions.

— answered 10 months ago by Malcolm Hollingsworth
answer permalink
1 Comment
  • thanks Malcolm i think this is exactly what i need. I have toyed with encodeuri / decoderui which would also work but as this app is already in production it would cause issues with current verisons. From what i see this solution is backward compatible.

    — commented 10 months ago by Martyn Joyce

Your Answer

Think you can help? Login to answer this question!