【发布时间】:2015-08-03 21:52:00
【问题描述】:
我正在创建一个 NSURL 作为请求发送给我已经设置好的 PHP 休息 API。下面是我的代码:
NSMutableString *url = [NSMutableString stringWithFormat:@"http://www.private.com/recievedata.php?item=%@&contact=%@&discovery=%@&summary=%@",__item,__contactDetails,__lostFound,__explain];
//The " ' " in PHP is a special character, so we have to escape it in the URL
//The two slashes are because the "\" itself is a special character in Objective C
NSString *formattedURL = [url stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];
NSURLSession *session = [NSURLSession sharedSession];
NSURL *address = [NSURL URLWithString:formattedURL];
但由于某种原因,每当我尝试使以下网址发生时,地址变量都会保存nil:
http://www.private.com/recievedata.php?item=hell\'&contact=hell&discovery=lost&summary=hell
从我的代码中可以看出,我必须在撇号前面添加“\”,因为 PHP 需要在其 URL 中转义“'”。但是这样做,似乎我违反了为NSURL 设定的一些要求。大家觉得呢?
【问题讨论】:
-
不要转义引号,而是使用
stringByAddingPercentEscapesUsingEncoding:正确编码 URL 中的特殊字符。 -
@rmaddy 我应该输入什么编码类型?
-
很可能是
NSUTF8StringEncoding,但这取决于服务器的期望。 -
@rmaddy 不工作,我的 url 需要这样的东西: \' 用于 PHP 的目的,但在 NSURLs 中不允许反冲。我该如何解决这个问题?
-
顺便说一句,我注意到您正在构建
GET请求,并将所有这些参数添加到 URL。您可以考虑使用POST请求(看起来您实际上是在发送数据)并将这些参数放在请求的正文中而不是 URL 中。
标签: objective-c nsurl nsurlsession