URL encoding in IOS
Luo chaohui (http://www.cnblogs.com/kesalin)
This article follows the "signature-non-commercial use-consistency" creation public agreement
The stringbyaddingpercentescapesusingencoding of nsstring can encode the URL parameter, but it is a small problem and will not encode all characters to be encoded. We can use the cfstringref
The cfurlcreatestringbyaddingpercentescapes function encapsulates this function.CodeAs follows:
-(Nsstring *) encodetopercentescapestring: (nsstring *) Input
{
// Encode all the reserved characters, per RFC 3986
// (< Http://www.ietf.org/rfc/rfc3986.txt >)
Nsstring * outputstr = (nsstring *)
Cfurlcreatestringbyaddingpercentescapes (kcfallocatordefault,
(Cfstringref) input,
Null,
(Cfstringref) @" ! * '();: @ & = + $ ,/? % # [] " ,
Kcfstringencodingutf8 );
Return Outputstr;
}
-(Nsstring *) decodefrompercentescapestring: (nsstring *) Input
{
Nsmutablestring * outputstr = [nsmutablestring stringwithstring: Input];
[Outputstr replaceoccurrencesofstring: @" + "
Withstring: @" "
Options: nsliteralsearch
Range: nsmakerange ( 0 , [Outputstr length])];
Return [Outputstr stringbyreplacingpercentescapesusingencoding: nsutf8stringencoding];
}
Test code:
Nsstring * testurl = @" Http://search.google.com? KEYWORDS = ($ # It's {A * 123}) 00! * '();: @ & = + $ ,/? % # [] " ;
Nslog ( @" Original: % @ " , Testurl );
Nsstring * encodestr = [self encodetopercentescapestring: testurl];
Nslog ( @" Encoded: % @ " , Encodestr );
Nsstring * encodestr2 = [testurl stringbyaddingpercentescapesusingencoding: nsutf8stringencoding];
Nslog ( @" Encoded2: % @ " , Encodestr2 );
Nsstring * decodestr = [self decodefrompercentescapestring: encodestr];
Nslog ( @" Decoded: % @ " , Decodestr );
The result is as follows:
Original: http://search.google.com? KEYWORDS = ($ # It's {A * 123}) 00! * '();: @ & = + $ ,/? % # []
>> encoded: HTTP % 3A % 2f % 2fsearch.google.com % 3 fkeywords % 3d % 28% 24% 23% 20it % 27 S % 20% 7ba % 2a123% 7D % 2900% 2a % 21% 27% 28% 3B % 3A % 29% 26% 3D % 2B % 24% 2C % 2f % 3f % 25% 23% 5B % 5d
encoded2: http://search.google.com? KEYWORDS = ($ % 23% 20it's % 20% 7ba * 123% 7D) 00! * '();: @ & = + $ ,/? % 25% 23% 5B % 5d
decoded: http://search.google.com? KEYWORDS = ($ # It's {A * 123}) 00! * '();: @ & = + $ ,/? % # []