当URL里面含有中文时

今天遇到一个蛋疼的问题,朋友写的服务端,url里面含有中文,ios客户端不能正确识别使用NSURLConnection进行网络请求的时候直 接报错:bad URL...当时就蛋疼菊紧了,本来一般情况下是服务端直接给我UTF-8编码过的url就我这边就可以了,无奈这家伙跟我一样也是个懒蛋,只要去 google寻找答案,

参考网址:http://www.iphonedevsdk.com/forum/iphone-sdk- development/39716-nsstring-utf-8-a.html,找到了CFStringRef CFURLCreateStringByAddingPercentEscapes(CFAllocatorRef allocator,

                       CFStringRef originalString,

                       CFStringRef charactersToLeaveUnescaped,

                       CFStringRef legalURLCharactersToBeEscaped,

                       CFStringEncoding encoding);这个方法,调转到该方法的声明解释如下:

/* Creates a copy or originalString, replacing certain characters with */
/* the equivalent percent escape sequence based on the encoding specified. */
/* If the originalString does not need to be modified (no percent escape */
/* sequences are missing), may retain and return originalString. */
/* If you are uncertain of the correct encoding, you should use UTF-8, */
/* which is the encoding designated by RFC 2396 as the correct encoding */
/* for use in URLs.  The characters so escaped are all characters that */
/* are not legal URL characters (based on RFC 2396), plus any characters */
/* in legalURLCharactersToBeEscaped, less any characters in */
/* charactersToLeaveUnescaped.  To simply correct any non-URL characters */
/* in an otherwise correct URL string, do: */

/* newString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, origString, NULL, NULL, kCFStringEncodingUTF8); */
 

NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                   (CFStringRef)urlString,
                                                                                   NULL,
                                                                                   NULL,
                                                                                   kCFStringEncodingUTF8);

通过这个方法编码之后,返回的encodedString就是通过kCFStringEncodingUTF8编码的字符串,这个方法可以直接用来转换含有中文的字符串,然后作为url进行使用。问题解决:)

你可能感兴趣的:(职场,url,iPhone,休闲)