1

Is there a simple way to escape a NSString so I can use it in a HTTP POST request?

I've tried stringByAddingPercentEscapesUsingEncoding, but the following:

[@"~!@#$%^&*()-+\"'" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]

gives me:

~!@%23$%25%5E&*()-+%22'

which is not usable in a HTTP POST query because the & is left unescaped; therefore the other end interprets whatever follows it as another argument.

houbysoft
  • 32,532
  • 24
  • 103
  • 156
  • Look up the URLEncoding category for NSString. It looks like it is under MIT License and you can find it by searching "NSString+URLEncoding.m" – Jesse Black Jan 21 '12 at 03:18
  • @Maudicus: thanks, that worked, I'm posting it as an answer for Googlers. – houbysoft Jan 21 '12 at 05:27
  • 1
    See also http://stackoverflow.com/questions/718429/creating-url-query-parameters-from-nsdictionary-objects-in-objectivec, http://stackoverflow.com/questions/1748981/nsurl-encoding-in-objc, http://stackoverflow.com/questions/2159341/nsstring-method-to-percent-escape-for-url – Isaac Jan 21 '12 at 05:32

1 Answers1

1

The following function, part of NSString+URLEncoding.m, does exactly what I need:

- (NSString *)encodedURLParameterString {
NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                       (CFStringRef)self,
                                                                       NULL,
                                                                       CFSTR(":/=,!$&'()*+;[]@#?"),
                                                                       kCFStringEncodingUTF8);
    return [result autorelease];
}
houbysoft
  • 32,532
  • 24
  • 103
  • 156