3

I want to encode my JSON to application/x-www-form-urlencoded

var req = URLRequest(url: url)
req.httpMethod = "POST"
req = JsonHelper.defineCommonHeaders(request: req)
var headers = req.allHTTPHeaderFields ?? [:]
headers["Content-Type"] = "application/x-www-form-urlencoded"
print(headers)

do {
    let jsonData = try encoder.encode(self)
    let jsonString = String(data: jsonData, encoding: .utf8)!
    req.httpBody = jsonData as Data
    print ("httpBody is: ", jsonString)
} catch {
    //TODO:error handling
}

sending my JSON from Postman is fine, however sending from Swift 4 does not work. I quess I need to encode empty key somewhere. There is great example POST request using application/x-www-form-urlencoded but it does not cover how to do it in Swift 4. What I have to change?

Au Ris
  • 4,541
  • 2
  • 26
  • 53
Robert
  • 525
  • 1
  • 6
  • 21
  • Have you tried adding another header: "Accept": "application/json" – u84six May 15 '18 at 23:08
  • I had. No luck. The problem is that `x-www-form-urlencoded` requires key: value (API of the client need key to be empty). But I have no idea how to add so basically it requires `""="{my_json_here}"`. I get this with manipulating strings, but it is still not accepting this. – Robert May 16 '18 at 08:12
  • Open postman, click on code, select language and try that code in your application. – Chanchal Chauhan May 16 '18 at 12:07
  • Tried this already. No luck. – Robert May 16 '18 at 12:34
  • Could you show us the postman example? Why don't you just use `application/json`? In `x-www-form-urlencoded` you would have to URL encode the JSON string. – Sulthan May 21 '18 at 14:09
  • 1
    I have asked third party api provider to change to application/json. Then all working like a charm, and my code is much tidier. – Robert May 22 '18 at 08:47

0 Answers0