电子邮件地址中的“+”号

时间:2010-03-24 16:01:15

标签: iphone objective-c iphone-sdk-3.0

我需要提交一个带有“+”标志的电子邮件地址,并在服务器上进行验证。但服务器会收到“aaa+bbb@mail.com”之类的电子邮件为“aaa bbb@mail.com”。

我将所有数据作为POST请求发送,并带有以下代码

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];

编码前的变量值为

&email=aaa+bbb@gmail.coma&userName=Asdfasdfadsfadsf&password=sdfasdf
编码后

是相同的

&email=aaa+bbb@gmail.coma&userName=Asdfasdfadsfadsf&password=sdfasdf

我用来发送请求的方法如下代码:

-(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;
}

3 个答案:

答案 0 :(得分:6)

电子邮件,用户名和密码需要-stringByAddingPercentEscapesUsingEncoding:转发。

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

但是,这不会逃避+,因为它是有效的URL字符。您可以使用更复杂的CFURLCreateStringByAddingPercentEscapes,或者为简单起见,只需将所有+替换为%2B

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

答案 1 :(得分:1)

HTTP服务器将+转义为空格。

您需要通过调用+

%2B作为CFURLCreateStringByAddingPercentEscapes转义

答案 2 :(得分:0)

您需要对加号进行urlencode。接收者认为这是一个加号必须变为%2B