How to Http Post Special Chars in Swift

Swift how to send symbols like &(*( with HTTP post

As Sulthan suggested, no predefined CharacterSet can be used for actual servers when you want to include some symbol characters in your POST data.

An example CharacterSet which I often use:

extension CharacterSet {
static let rfc3986Unreserved = CharacterSet(charactersIn:
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")
}

let postValue = "(1&*^&&2"
let postString = "app_log_pass=\(postValue.addingPercentEncoding(withAllowedCharacters: .rfc3986Unreserved)!)"
print(postString) //->app_log_pass=%281%26%2A%5E%26%262

Another CharacterSet which would work for usual PHP servers:

extension CharacterSet {
static let queryValueAllowed = CharacterSet.urlQueryAllowed.subtracting(CharacterSet(charactersIn: "&+="))
}

let postValue = "(1&*^&&2"
let postString = "app_log_pass=\(postValue.addingPercentEncoding(withAllowedCharacters: .queryValueAllowed)!)"
print(postString) //->app_log_pass=(1%26*%5E%26%262

Anyway, you need to escape the key and the value separately, to prevent escaping the separator =.


ADDITION

An example of escaping multiple key-value pairs:

extension String {
var queryValueEscaped: String {
return self.addingPercentEncoding(withAllowedCharacters: .queryValueAllowed)!
}
}

let params: [String: String] = [
"app_log_usn": "OOPer",//usn_text_field.text!,
"app_log_pass": "(1&*^&&2"//pass_text‌​_field.text!
]
let postString = params.map {"\($0.key)=\($0.value.queryValueEscaped)"}.joined(separator: "&")
print(postString) //->app_log_usn=OOPer&app_log_pass=(1%26*%5E%26%262

Assuming each key is made of safe characters and no need to escape.

How to send '&' character in HTTP request body?

As you can read in the attached links you have to encode the ampersand sign.

encodeURIComponent('&') gives "%26"

Thus, you have to replace all ampersands with %26 or use encodeURIComponent(str) in your code.

escaping ampersand in url

How can I send the "&" (ampersand) character via AJAX?

URLRequest encoding not catching special characters

This code has a number of likely problems:

  • You're uploading a blob of JSON data in a single URL-encoded form field and not using any other fields. Why not just make the upload format be JSON and ditch the URL encoding entirely?
  • You're trying to URL-encode the whole "fieldname=value" when you should just be URL-encoding the value part.
  • The alphanumerics character set is WAY too broad, including anything that looks like a number. The legal character set for a URL is much, much smaller than that.

BTW, I'm fairly certain that even URLQueryAllowedCharacterSet is too broad for a single query string field, because it allows characters like equals signs and ampersands that are reserved as field delimiters in the normal use of query strings.

For maximum safety, you should instead use your own character set that contains only the unreserved characters:

    [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuv"
"wxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"]

Or better yet, use NSURLComponents. It has properties specifically for constructing query strings.

How to use special character in NSURL?

Swift 2

let original = "http://www.geonames.org/search.html?q=Aïn+Béïda+Algeria&country="
if let encodedString = original.stringByAddingPercentEncodingWithAllowedCharacters(
NSCharacterSet.URLFragmentAllowedCharacterSet()),
url = NSURL(string: encodedString)
{
print(url)
}

Encoded URL is now:

"http://www.geonames.org/search.html?q=A%C3%AFn+B%C3%A9%C3%AFda+Algeria&country="

and is compatible with NSURLSession.

Swift 3

let original = "http://www.geonames.org/search.html?q=Aïn+Béïda+Algeria&country="
if let encoded = original.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),
let url = URL(string: encoded)
{
print(url)
}

How to use special characters \n in URL

strUrl = strUrl.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!

let url = URL.init(string: strUrl)

let requestURL = URLRequest(url: url!)
  • You need to add addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) method to allow URL Query.


Related Topics



Leave a reply



Submit