URL 編碼:CFURLCreateStringByAddingPercentEscapes

 If you have tried to send any information using a GET web request, you would have come cross an annoying problem, That annoying problem is making sure that the URL is corrently encoded.

  The issue is that by default most of these methods leave characters such as & = ? within a URL, as they are strictly speaking valid. The problem is that these characters have special meanings in a GET request, and will more than likely make your request invalid.

   也就是說,你提供的 URL 字符串 裏面可能包含某些字符,比如‘$‘ ‘&’ ‘?’...等,這些字符在 URL 語法中是具有特殊語法含義的,

比如 URL :http://www.baidu.com/s?wd=%BD%AA%C3%C8%D1%BF&rsv_bp=0&rsv_spt=3&inputT=3512 

中 的 & 起到分割作用 等等,如果 你提供的URL 本身就含有 這些字符,就需要把這些字符 轉化爲 “%+ASCII” 形式,以免造成衝突。

  這就引入:CFURLCreateStringByAddingPercentEscapes 函數。

  該函數將 將要添加到URL的字符串進行特殊處理,如果這些字符串含有 &, ? 這些特殊字符,用“%+ASCII” 代替之。

CFURLCreateStringByAddingPercentEscapes(

  kCFAllocatorDefault,

  (CFStringRef)parameter,

  NULL,

   CFSTR(":/?#[]@!$&’()*+,;="),     // 確定 parameter 字符串中含有:/?#[]@!$&’()*+,;=這些字符時候,這些字符需要被轉化,以免與語法衝突。

  kCFStringEncodingUTF8

);

 


例如: 建立一個 NSURL 的 category

複製代碼
@implementation NSURL (mm)

+ (NSURL *)URLWithBaseString:(NSString *)baseString parameters:(NSDictionary *)parameters{   
    
    NSMutableString *urlString =[NSMutableString string];   //The URL starts with the base string[urlString appendString:baseString];   

    [urlString appendString:baseString];

    NSString *escapedString;   

    NSInteger keyIndex = 0;   
    
    for (id key in parameters) {   
      
      //First Parameter needs to be prefixed with a ? and any other parameter needs to be prefixed with an & 
      if(keyIndex ==0) { 
          escapedString =(NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)[parameters valueForKey:key], NULL, CFSTR(":/?#[]@!$&’()*+,;="), kCFStringEncodingUTF8);   
          
          [urlString appendFormat:@"?%@=%@",key,escapedString]; 
          [escapedString release]; 
          
      }else{   
          escapedString =(NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)[parameters valueForKey:key], NULL, CFSTR(":/?#[]@!$&’()*+,;="), kCFStringEncodingUTF8);   
          
          [urlString appendFormat:@"&%@=%@",key,escapedString]; 
          [escapedString release];  
      }   
      keyIndex++; 
    }   
    return [NSURL URLWithString:urlString];   
}

@end
複製代碼

調用測試:

    NSString * baseString = @"http://twitter.com/statuses/update.xml";
    NSDictionary*dictionary=[NSDictionary dictionaryWithObjectsAndKeys:@"This is my status",@"status",@"meng ya", @"meyers",nil];
    NSURL * url = [NSURL URLWithBaseString:baseString parameters:dictionary];
    NSLog(@"the url : %@", url);

輸出:

the url : http://twitter.com/statuses/update.xml?status=This%20is%20my%20status&meyers=meng%20ya

 另外就是 CFURLCreateStringByAddingPercentEscapes  將自動將待轉化的字符串中的空格 轉化爲 : %20, 即 空格字符的 ASCII,

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章