StringByAddingPercentEscapes not working on ampersands, question marks etc
I'm sending a request from my iphone-application, where some of the arguments are text that the user can enter into textboxes. Therefore, I need to HTML-encode them.
Here's the problem I'm running into:
NSLog(@"%@", testText); // Test & ?
testText = [testText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", testText); // Test%20&%20?
As you can see, only the spaces are encoded, making the server disregard everything past the ampersand for the argument.
Is this the advertised behaviour of stringByAddingPercentEscapes? Do I have to manua开发者_运维百科lly replace every special character with corresponding hex code?
Thankful for any contributions.
They are not encoded because they are valid URL characters.
The documentation for stringByAddingPercentEscapesUsingEncoding:
says
See CFURLCreateStringByAddingPercentEscapes for more complex transformations.
I encode my query string parameters using the following method (added to a NSString
category)
- (NSString *)urlEncodedString {
CFStringRef buffer = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)self,
NULL,
CFSTR("!*'();:@&=+$,/?%#[]"),
kCFStringEncodingUTF8);
NSString *result = [NSString stringWithString:(NSString *)buffer];
CFRelease(buffer);
return result;
}
精彩评论