在 NSURL 和 iOS8+ 中使用引号

Using quote marks with NSURL and iOS8+

我正在尝试使用 NSURL 形成请求。 我的代码:

(某处)

#define CLASS_URL @"https://www.someurl.com/xyz"

(某处)

NSString *className = @"className";

然后我的主要代码:

NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"%@&name=\"%@\"", CLASS_URL, className]];

我已经阅读了很多关于在 Whosebug 上添加引号的答案,说明我应该使用什么。我试过了:

但是 none 的答案似乎有效。调用 NSLog(@"URL: %@", url);

时总是得到 (null)

有人知道如何正确执行此操作吗?

编辑: 我尝试按照建议使用 stringByAppendingString,但仍然无法正常工作。

NSString *tmp = [CLASS_URL stringByAppendingString:[NSString stringWithFormat:@"&name=\"%@\"",className]];

Expected result:

www.someurl.com/xyz&name="className"

我需要双引号以防用户输入 space.

您预期的 URL 不正确。

I need double quotes in case user types a space.

双引号不会使 spaces 在 URL 中合法。空格是保留的,并且必须用百分比编码,无论是否在引号中。双引号不是未保留的 space 的一部分,因此如果您需要它们也应该被引用(但这不会让您免于编码 spaces)。

构建它的方法是对要发送的字符串进行编码:

NSString *className = @"className with space";
NSString *quotedClassName = [className stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSString *urlString = [NSString stringWithFormat:@"%@?name=%@", CLASS_URL, quotedClassName];
NSURL *url = [[NSURL alloc] initWithString:urlString];

这将编码为:

https://www.someurl.com/xyz?name=className%20with%20space

注意我已经完全删除了双引号。如果你真的需要它们,那么你可以通过让你的原始字符串包含它们,然后对它们进行编码来获得它们:

NSString *className = @"\"className with space\"";
NSString *quotedClassName = [className stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

这将编码为:

https://www.someurl.com/xyz?name=%22className%20with%20space%22

(我还修复了您的查询参数,这可能只是一个拼写错误。查询与路径由 ? 分隔,而不是 &。)

URL 中的引号需要用转义引号替换:

#define CLASS_URL @"https://www.someurl.com/xyz"

NSString *className = @"className";
NSString *query = [NSString stringWithFormat:@"name=\"%@\"", className];

// URL encode the query
query = [query stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

NSString *urlString = [NSString stringWithFormat:@"%@?%@", CLASS_URL, query];
NSURL *url = [NSURL URLWithString:urlString];

NSLog(@"URL: %@", url);

URL: https://www.someurl.com/xyz?name=%22className%22

此外,“&”需要替换为 ?,查询字符串以 ? 开头,后续参数以“&”分隔。