[IOS] Question about URL encoding in IOS
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. The Code is as follows:
CPP Code
- -(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:
CPP 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:
CPP Code
- > 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! * '();: @ & = + $ ,/? % # []
Post from: