objective-c - 将 URL 解析到服务器时无法处理方括号 (=[])

标签 objective-c parsing url webserver url-parsing

我正在从我的 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.

如果您使用

创建 URL
NSString *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/

相关文章:

c - NSUInteger 与 NSInteger、int 与 unsigned 以及类似情况

iphone - CAGradientLayer,不能很好地调整大小,旋转时撕裂

c++ - Wavefront OBJ 解析 - 为什么我总是得到不正确的数据作为输出?

javascript - Chrome.webrequest.onBeforeRequest 多次调用自身

url - 在 IIS 7.5 中重写服务器变量

ios - 将希伯来语文本保存到 NSUserDefaults 返回奇怪的编码

php - 如何从以加号 (+) 开头的行创建段落

python - 如何将主链接添加到子链接html,以便可以调用该链接?

ruby-on-rails - Rails 是否维护多个 URL 数组参数的顺序

objective-c - 如何从登录项属性文件 (com.apple.loginitems.plist) 解析 NSData