守望远方

热爱生活 热爱工作 守望远方
ios网络请求特殊字符&处理

原文地址:http://www.xuebuyuan.com/2039420.html

CFURLCreateStringByAddingPercentEscapes

在作项目的的时候,一般都要用到网络搜索,所以链接(也就是NSURL)也会总是存在一些中文或者特殊字符,但是对于网址是不允许存在一些特殊字符的,所以在这里我列出一个对一个字符串进行NSUTF-8转码的宏,希望可以给大家提供方便。

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
);

 

#define NSUTF8String(v) ((NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)(v),  NULL, CFSTR(":/?#[]@!$’()*+,;"), kCFStringEncodingUTF8)) 这里记得调用这个宏之后要对获得的字符串进行一次release

posted on 2016-05-09 18:42  守望远方  阅读(2461)  评论(0编辑  收藏  举报