Nicolas Miari
Nicolas Miari

Reputation: 16246

Confusion Regarding Escaping Special Characters in URL Parameters

Background:

I have read several questions answers here, but the more I read, it only gets more confusing.

Task:

I need to send a POST URL request with "trailing" parameters in the URI, like this:

http://www.myhostname.com/functionName?parameter1=value1&parameter2=value2

Typically, I will create the parameter string with a format and insert the values for each parameter, like this:

let value1 = "Hello"
let value2 = "World"

let parameterString = "?parameter1=\(value1)&parameter2=\(value2)"

let requestURL = baseURL.URLByAppendingPathComponent("\(fucntionName)\(parameterString)")

Questions:

  1. Do I need to percent-escape the "?" before the first parameter?
  2. Do I need to percent-escape the "&" before each subsequent parameter?
  3. Do I need to percent-escape the "=" between each parameter name and its value?
  4. Do I need to percent-escape the "." if some parameter's value is a file name with an extension?
  5. Should I escape using URLQueryAllowedCharacterSet, or do I need to define a custom character set?

Update: If I escape using NSCharacterSet.URLQueryAllowedCharacterSet() and print() the resulting string, the ?, = and & remain intact. If I use that string to instantiate an NSURL and then print its path property (that is, a String), I get the same output.

But if I pass said NSURL instance as-is to print(), the ? alone gets percent-escaped (into %3F).

Upvotes: 0

Views: 236

Answers (1)

Tj3n
Tj3n

Reputation: 9923

To create your String contain the URL first by combine Base URL with the param first and encode it using stringByAddingPercentEncodingWithAllowedCharacters then only turns it to URL, the "? & = . /" should not be percent escaped in the URL

let escapedSearchText = searchText.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())!

let urlString = String(format:"%@/%@?parameter1=%@&parameter2=%@",hostName, functionName,value1, value2)
//http://www.myhostname.com/functionName?parameter1=value1&parameter2=value2

let url = NSURL(string: urlString)
return url!

Upvotes: 1

Related Questions