FMEngine icon indicating copy to clipboard operation
FMEngine copied to clipboard

Ampersands and generatePOSTBodyFromDictionary

Open prendio2 opened this issue 14 years ago • 1 comments

I encountered an error when fetching data for artists with ampersands in their name, like "Simon & Garfunkel"

The ampersand needs to be url endcoded or the artist named will be concatenated, in this case returning details for "Simon".

I added the following function, originally found at http://deusty.blogspot.com/2006/11/sending-http-get-and-post-from-cocoa.html

- (NSString *)urlEncodeValue:(NSString *)str
{
    NSString *result = (NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, CFSTR("?=&+"), kCFStringEncodingUTF8);
    return [result autorelease];
}

and adjusted generatePOSTBodyFromDictionary as follows

[rawBody appendString:[NSString stringWithFormat:@"&%@=%@", key, [self urlEncodeValue:[dict objectForKey:key]]]];

prendio2 avatar Apr 02 '10 17:04 prendio2

This also affects posting songs with ampersand, e.g. Belle & Sebastian to last.fm using either track.scrobble or track.updateNowPlaying.

You can run into problems if you apply the patch above because some values in the dictionary might not be NSStrings so you'll have to check for that, otherwise the patch above works.

You might also want to consider encoding more characters to comply with RFC 3986 (http://www.ietf.org/rfc/rfc3986.txt) Something like this would do that: NSString result = (NSString) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8);

hjaltij avatar Mar 08 '11 15:03 hjaltij