Zac Powell Zac Powell - 3 months ago 38
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:@"https://dev.flippie.com/OAuth/token"]];
[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?

Answer

Escape the string with stringByAddingPercentEscapesUsingEncoding:

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