我正在从我的 iPhone 应用调用以下 URL
NSString *resourcePath = [NSString stringWithFormat:@"/sm/search?limit=100&term=%@&types[]=users&types[]=questions", searchTerm];
但是,当调用服务器的时候,发现实际发送的URL是这个
/sm/search?term=mi&types%5B%5D=questions&limit=100
如何解决这个问题,以便将正确的 URL 发送到服务器?
最佳答案
我假设你使用的是 NSURL
方法
initWithScheme:host:path:
创建 URL。根据文档,此方法使用 stringByAddingPercentEscapesUsingEncoding:
方法自动转义路径。
方括号被转义,因为它们在 RFC 1738 - Uniform Resource Locators (URL) 意义上是“不安全的” :
Characters can be unsafe for a number of reasons. [...] Other characters are unsafe because gateways and other transport agents are known to sometimes modify such characters. These characters are "{", "}", "|", "\", "^", "~", "[", "]", and "`".
All unsafe characters must always be encoded within a URL.
如果您使用
创建 URLNSString *s = [NSString stringWithFormat:@"http://server.domain.com/sm/search?limit=100&term=%@&types[]=users&types[]=questions", searchTerm];
NSURL *url = [[NSURL alloc] initWithString:s];
然后不添加转义序列,因为 initWithString
期望字符串包含任何必要的百分比转义代码。
关于objective-c - 将 URL 解析到服务器时无法处理方括号 (=[]),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13873460/