创建NSURL时的URL错误

时间:2012-08-04 06:39:21

标签: iphone nsurl

我在服务器上发出请求,在URL中有空格

http://xxxxxxxx.com/api/api.php?func=showAllwedsdwewsdsd&params [] =%沙特&20Arab放大器; PARAMS [] =所有

我收到了错误的错误网址,

我用过

   downloadURL = [downloadURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

但是由于这个原因我得到了奇怪的网址

 http://sdsdsdsdsdsd.com/api/api.php?func=showAllsdsd&params5262721536=Saudi              0X0P+0rabia&params5 8288=All

我也在使用

  downloadURL= [downloadURL stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

但又是一个奇怪的网址

     http://xxxxxxxxx.com/api/api.php?func=showsdsdsd&params[]=Saudi 0X1.240DC0D824P-807rabia&params[]=All

请帮助我如何解决此问题

编辑粘贴大部分代码

   PropertyXMLDownloader *download=[[PropertyXMLDownloader alloc]init];
  [download setDelegate:self];
   firstAppDelegate *del=(firstAppDelegate *)[[UIApplication sharedApplication]delegate];
   NSLog(@"Country is %@",del.country);
   NSLog(@"State is %@",del.state);
//  del.country=[del.country stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

   NSString *downloadURL=[NSString stringWithFormat:@"http://xxxxxxxx.com/api/api.php?func=showAll&params[]=Saudi Arabia&params[]=%@",@"all"];
      // downloadURL= [downloadURL stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
       //downloadURL = [downloadURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

   NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@" "];
   downloadURL = [[downloadURL componentsSeparatedByCharactersInSet: doNotWant]    componentsJoinedByString:@"%20"];


    NSLog(downloadURL); 
    [download startDownloading:downloadURL];

3 个答案:

答案 0 :(得分:1)

试试这个。

NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@" "];
downloadURL = [[downloadURL componentsSeparatedByCharactersInSet: doNotWant]   componentsJoinedByString:@"%20"];

答案 1 :(得分:1)

也许%20被视为数据参数,例如%@或%g。尝试使用

定义NSString
NSString *urlString = [NSString stringWithFormat:@"http://xxxxxxxx.com/api/api.php?func=showAllwedsdwewsdsd&params[]=Saudi%20Arab&params[]=all"];

你会看到一个警告。通过在其前面添加另一个符号来“转义”百分号:

NSString *urlString = [NSString stringWithFormat:@"http://xxxxxxxx.com/api/api.php?func=showAllwedsdwewsdsd&params[]=Saudi**%**%20Arab&params[]=all"];

并且警告消失了。

答案 2 :(得分:0)

你的问题是:

NSLog(downloadURL); 

尝试将其替换为:

NSLog(@"%@", downloadURL); 

一切都会奏效。

您可以使用stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding并忘记所有解决方法。

(解释:由于downloadURL包含%符号,因此它不能很好地与NSLog一起使用,后者期望将格式字符串作为其第一个参数,其中%符号标识要替换的占位符。