views:

105

answers:

3

Hi. I need to submit an email address with a "+" sign and validate in on server. But server receives email like "[email protected]" as "aaa [email protected]".

I send all data as POST request with following code

NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", url, @"/signUp"]];

NSString *post = [NSString stringWithFormat:@"&email=%@&userName=%@&password=%@",
                      user.email, 
                      user.userName, 
                      user.password];

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];

NSData* data = [self sendRequest:url postData:postData];

post variable before encoding has value

&[email protected]&userName=Asdfasdfadsfadsf&password=sdfasdf

after encoding it is same

&[email protected]&userName=Asdfasdfadsfadsf&password=sdfasdf

Method I use to send request looks like following code:

-(id) sendRequest:(NSURL*) url postData:(NSData*)postData {
    // Create request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

    NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];

    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];

    NSURLResponse *urlResponse;

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil];

    [request release];

    return data;
}
A: 

The + is being unescaped as a space by the HTTP server.

You need to escape the + as %2B by calling CFURLCreateStringByAddingPercentEscapes

SLaks
A: 

You need to urlencode the plus sign. It must become %2B for the receiver to think it's a plus sign.

klausbyskov
+2  A: 

The email, user name and password need to be escaped by -stringByAddingPercentEscapesUsingEncoding:.

NSString *post = [NSString stringWithFormat:@"&email=%@&userName=%@&password=%@",
                  [user.email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                  ...

However, this won't escape the + since it is a valid URL character. You may use the more sophiscated CFURLCreateStringByAddingPercentEscapes, or for simplicity, just replace all + by %2B:

NSString *post = [NSString stringWithFormat:@"&email=%@&userName=%@&password=%@",
                  [[user.email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
                   stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"], ...
KennyTM