开发者

StringByAddingPercentEscapes not working on ampersands, question marks etc

开发者 https://www.devze.com 2023-03-28 04:30 出处:网络
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.

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消