kraftydevil
kraftydevil

Reputation: 5246

How to properly encode UTF-8 in iOS using NSMutableURLRequest?

I am trying to send information to a login web service but certain characters are giving me trouble.

For example, if the password is something like h+4hfP, the web service rejects it because the plus sign ('+') is not properly encoded to %2B.

The web service uses UTF-8 encoding so I have been building an NSData object with this NSString method, - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding; choosing NSUTF8StringEncoding as the encoding.

This doesn't seem to be enough though.

The problem could also be with how I'm building an NSMutableURLRequest:

NSData *postData = [@"h+4hfP" dataUsingEncoding:NSUTF8StringEncoding];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:contentLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];

How can I ensure the encoding is done properly?

Upvotes: 1

Views: 4820

Answers (3)

Marcelo dos Santos
Marcelo dos Santos

Reputation: 859

This can be a solution: I was facing this problem. After some hours and search, I discovered this: http://madebymany.com/blog/url-encoding-an-nsstring-on-ios

Solution: 1st: You must create a method or class with content:

-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding withString:(NSString *) str{
return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
                                                           (CFStringRef)str,
                                                           NULL,
                                                           (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                                           CFStringConvertNSStringEncodingToEncoding(encoding)));

}

2nd: Use:

NSString *stringToSend = [self urlEncodeUsingEncoding:NSUTF8StringEncoding withString:stringToBeVerifyed];

Then

NSData *postData = [stringToSend dataUsingEncoding:NSUTF8StringEncoding];
[...]

Upvotes: 0

Fawad Masud
Fawad Masud

Reputation: 12344

Use

 [theRequest setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];

Upvotes: 3

John
John

Reputation: 2755

You could percent encode the string before representing it as NSData:

NSString *password = [@"h+4hfP" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
NSData *postData = [password dataUsingEncoding:NSUTF8StringEncoding];
...

Upvotes: 0

Related Questions