转义通过http正文发送的电子邮件字符串中的特殊字符

时间:2015-08-07 10:28:11

标签: ios http

我有一个iOS应用程序,通过http主体向服务器发送电子邮件地址,如下所示:

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

除非电子邮件地址包含特殊字符(例如“+”),然后制作http请求,否则此工作正常。 如何在电子邮件字符串中转义可能导致和发出的任何字符?

2 个答案:

答案 0 :(得分:1)

使用stringByAddingPercentEscapesUsingEncoding:

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

答案 1 :(得分:0)

在iOS 9.0中不推荐使用stringByAddingPercentEscapesUsingEncoding的先前选择的答案。新方法是stringByAddingPercentEncodingWithAllowedCharacters

NSString *escapedEmail = [email stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];

内置了一些不同的角色集,您可以创建自己的角色集。

@interface NSCharacterSet (NSURLUtilities)
+ (NSCharacterSet *)URLUserAllowedCharacterSet;
+ (NSCharacterSet *)URLPasswordAllowedCharacterSet;
+ (NSCharacterSet *)URLHostAllowedCharacterSet;
+ (NSCharacterSet *)URLPathAllowedCharacterSet;
+ (NSCharacterSet *)URLQueryAllowedCharacterSet;
+ (NSCharacterSet *)URLFragmentAllowedCharacterSet;