我已经在Safari中输入了URL http://localhost:8080/a?a=1\\tb?b=2
,它按预期运行,但是当使用NSURL URLWithString时,它返回nil。(服务器也需要\t
字符)
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/a?a=1\\tb?b=2"];
问题是,您需要对URL字符串中的值进行百分比编码。服务器接收到它后,会将URL中的此百分比编码的字符串解码为所需的值。
但是您可以使用NSURLComponents
而不是对百分比进行编码。例如,如果希望a
的值为@"1\\tb"
,则可以执行以下操作:
NSURLComponents *components = [NSURLComponents componentsWithString:@"http://localhost:8080"];
components.queryItems = @[
[NSURLQueryItem queryItemWithName:@"a" value:@"1\\tb"],
[NSURLQueryItem queryItemWithName:@"b" value:@"2"]
];
NSURL *url = components.URL;
收益:
http://localhost:8080?a=1%5Ctb&b=2
或者,如果您希望它在与a
(即%09
)相关联的值中使用制表符:
NSURLComponents *components = [NSURLComponents componentsWithString:@"http://localhost:8080"];
components.queryItems = @[
[NSURLQueryItem queryItemWithName:@"a" value:@"1\tb"],
[NSURLQueryItem queryItemWithName:@"b" value:@"2"]
];
NSURL *url = components.URL;
收益:
http://localhost:8080?a=1%09b&b=2
仅取决于您的服务器需要两个字符,\
后跟t
(第一个示例)还是单个\t
字符(第二个示例)。无论哪种方式,NSURLComponents
的各自使用都将为您处理百分比编码,并且服务器将对其进行解码。
关于它的价值,一个警告是+
字符,NSURLComponents
不会为您百分比编码(因为从技术上讲,URL查询中允许+
字符)。问题是大多数Web服务器将+
字符解释为空格字符(按x-www-form-urlencoded
spec)。如果您需要传递文字+
字符,则可能要替换这些+
字符,如Apple所建议的那样:
NSURLComponents *components = [NSURLComponents componentsWithString:@"http://localhost:8080"];
components.queryItems = @[
[NSURLQueryItem queryItemWithName:@"q" value:@"Romeo+Juliet"]
];
components.percentEncodedQuery = [components.percentEncodedQuery stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
NSURL *url = components.URL;