4

I am calling the following URL from my iPhone app

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

However, when the server call is made, I found that the actual URL sent was this

/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?

Zhen
  • 12,361
  • 38
  • 122
  • 199

1 Answers1

3

I assume that you use the NSURL method

initWithScheme:host:path:

to create the URL. According to the documentation, this method automatically escapes path with the stringByAddingPercentEscapesUsingEncoding: method.

The square brackets are escaped, because they are "unsafe" in the sense of RFC 1738 - Uniform Resource Locators (URL):

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 within a URL.

If you create the URL with

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 percent escape codes.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 1
    It should be noted that if the server can't handle the escaped URL that's a problem on the server side. – Hot Licks Dec 16 '12 at 13:29
  • I am actually using RESTKIT Client for this "[[RKClient sharedClient] get:resourcePath usingBlock:^(RKRequest *request)" and the resourcepath only accepts a string – Zhen Dec 16 '12 at 14:56
  • @Zhen: I can't really help you with RestKit, because I haven't used it yet. I have browsed through the source code and is seems that RestKit consequently escapes all query parameters, which seems to be "the right thing", according to the cited RFC. So my answer can only help to explain the problem. Note also Hot Licks' comment that the server should handle this. – Martin R Dec 16 '12 at 16:50