Zac Powell Zac Powell - 6 months ago 56
HTTP Question

Escape special characters in email string sent via http body

I have an iOS app that sends an email address to a server via the http body as below:

NSString *post = [NSString stringWithFormat:@"grant_type=password&username=%@&password=%@",emailAddress,password];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@""]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

This works fine unless the email address contains special characters ('+' for example) which then brakes the http request.
How can i escape any characters that might cause and issue within the email string?


Escape the string with stringByAddingPercentEscapesUsingEncoding:

NSString *post = [NSString stringWithFormat:@"grant_type=password&username=%@&password=%@", [emailAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], password];