Search code examples
ipadunicodeutf-8ios5.1unicode-string

iOS: Issues with sending unicode text on server


I have come across really frustrating issue related to Unicode text and I am not able to do anything more to fix it. I am using following code to store English and Japanese texts on server from iPad.

    __block ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL: [NSURL URLWithString:url]];
    request.defaultResponseEncoding = NSUTF8StringEncoding;
    [request addRequestHeader:@"Content-Type" value:@"charset=UTF-8;"];

    NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
    [request appendPostData:data];

The weird thing is English text(in the same texts) gets stored fine on server but not Japanese. They get converted into some garbage text. For example When I UTF8 encode to " This is test フロントドアに表示されたアメックスのステッカーはありますか" text, it stored as "This is test フロントドアã«è¡¨ç¤ºã•ã‚ŒãŸã‚¢ãƒ¡ãƒƒã‚¯ã‚¹ã®ã‚¹ãƒ†ãƒƒã‚«ãƒ¼ã¯ã‚ã‚Šã¾ã™ã‹ï¼Ÿ".

Could anyone please point me what's going wrong here? Thanks.

[EDIT]

From ASIHTTPRequest document,

Sending a form POST with ASIFormDataRequest

To send POST data in a manner compatible with web page forms, use the included. 
ASIFormDataRequest subclass. ***Data is posted in ‘application/x-www-form-urlencoded’ 
format, or ‘multipart/form-data’ format when uploading binary data*** or files. Data in 
files is read as needed from disk, so POSTing large files is OK, as long as your 
web server is setup to handle them.

So I converted my code to use ASIHTTPRequest instead of ASIFormDataRequest but still no luck!

    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL: [NSURL URLWithString:url]];
    [request setDefaultResponseEncoding:NSUTF8StringEncoding];
    [request setRequestMethod:@"POST"];
    [request addRequestHeader:@"Content-Type" value:@"charset=UTF-8;"];

    NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
    [request appendPostData:data];

Solution

  • Following worked! You have to have value = "text/json; charset=utf-8" for content-type. Just setting charset won't work!!

        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL: [NSURL URLWithString:url]];
        [request setDefaultResponseEncoding:NSUTF8StringEncoding];
        [request setRequestMethod:@"post"];
        [request addRequestHeader:@"content-type" value:@"text/json; charset=utf-8"];