您的位置:首页 > 产品设计 > UI/UE

URL Loading System Programming Guide-Encoding URL Data(URL数据编码)

2015-03-09 09:49 387 查看
来源自:URL Loading System Programming Guide

为了编码URL字符串,可以使用Core Foundatin的CFURLCreateStringByAddingPercentEscapesCFURLCreateStringByReplacingPercentEscapesUsingEncoding函数。

根据 RFC 3986,在 URL 中的保留的字符如下:

reserved    = gen-delims / sub-delims

gen-delims  = ":" / "/" / "?" / "#" / "[" / "]" / "@"

sub-delims  = "!" / "$" / "&" / "'" / "(" / ")"
/ "*" / "+" / "," / ";" / "="


因此,为URL正确编码包含在 URL 中UTF 8 字符串,您应该执行以下操作:

CFStringRef originalString = ...

CFStringRef encodedString = CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
originalString,
NULL,
CFSTR(":/?#[]@!$&'()*+,;="),
kCFStringEncodingUTF8);


如果你想要解码URL片段,首先必须将URL字符串拆分成其组成部分 (字段和路径部分). If you do not decode it,you will be unable to tell the difference (for example) between an encoded ampersand that was originally part of the contents of a field and a bare ampersand that indicated the end of the field. 。

在将URL分成几部分后,可以解码每个部分,如下所示:

CFStringRef decodedString = CFURLCreateStringByReplacingPercentEscapesUsingEncoding(
kCFAllocatorDefault,
encodedString,
CFSTR(""),
kCFStringEncodingUTF8);


参考:

URL 编码:CFURLCreateStringByAddingPercentEscapes

iOS : How to do proper URL encoding?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  url encode decode