I need to submit an email address with a "+
" sign and validate in on server. But server receives email like "aaa+bbb@mail.com
" as "aaa bbb@mail.com
".
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=aaa+bbb@gmail.coma&userName=Asdfasdfadsfadsf&password=sdfasdf
after encoding it is same
&email=aaa+bbb@gmail.coma&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;
}
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"], ...
The +
is being unescaped as a space by the HTTP server.
You need to escape the +
as %2B
by calling CFURLCreateStringByAddingPercentEscapes
You need to urlencode the plus sign. It must become %2B
for the receiver to think it's a plus sign.
精彩评论