Cannot handle square brackets (= []) when parsing a URL on a server

I am calling the following url from my iPhone application

NSString *resourcePath = [NSString stringWithFormat:@"/sm/search?limit=100&term=%@&types[]=users&types[]=questions", searchTerm]; 

However, when the server call was made, I found that the actual URL was provided

 /sm/search?term=mi&types%5B%5D=questions&limit=100 

How can I resolve this so that the correct URL is sent to the server?

+4
source share
1 answer

I assume you are using the NSURL method

 initWithScheme:host:path: 

to create a url. According to the documentation, this method automatically skips the path using the stringByAddingPercentEscapesUsingEncoding: method.

Square brackets are escaped because they are β€œunsafe” in the sense of RFC 1738 - Uniform Resource Locators (URLs) :

Characters can be unsafe for a number of reasons. [...] Other characters are unsafe because gateways and other transport agents are known to sometimes modify such characters. These characters are "{", "}", "|", "\", "^", "~", "[", "]" and "` ".

All unsafe characters must always be encoded in the URL.

If you create a url using

 NSString *s = [NSString stringWithFormat:@"http://server.domain.com/sm/search?limit=100&term=%@&types[]=users&types[]=questions", searchTerm]; NSURL *url = [[NSURL alloc] initWithString:s]; 

then no escape sequences are added because initWithString expects the string to contain any necessary percentage escape codes.

+3
source

All Articles