1

I want to create the body of POST method with

Content-Type: application/x-www-form-urlencoded

I'have got a dictionary

let params = ["key":"val","key1":"val1"]

I've tried to convert and escape dictionary using URLComponents. But have not found in the HTTP specifications those escape methods are the same.

Does somebody know a correct solution to do this?

I've looked at

https://datatracker.ietf.org/doc/html/draft-hoehrmann-urlencoded-01

https://www.rfc-editor.org/rfc/rfc1866

https://www.rfc-editor.org/rfc/rfc1738

https://www.rfc-editor.org/rfc/rfc3986

Community
  • 1
  • 1
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194

1 Answers1

3

You can and should create the body with NSURLComponents:

let components = NSURLComponents()

components.queryItems = [ 
    URLQueryItem(name: "key", value: "val"), 
    URLQueryItem(name: "key1", value: "val1")
]
if let query = components.query {
    let request = NSMutableURLRequest()

    request.url = ...
    request.allHTTPHeaderFields = [ "Content-Type": "application/x-www-form-urlencoded"]
    request.httpBody = query.data(using: .utf8)
}

NSURLComponents creates valid URLs from data, and parses valid URLs to its components. The body of a HTTP post request with the content type above should contain the parameters as URL query (see How are parameters sent in an HTTP POST request?).

NSURLComponents is a good choice because it ensures conformity to the standard.

see also: Wikipedia and W3C.

clemens
  • 16,716
  • 11
  • 50
  • 65