den330 den330 - 5 months ago 33
JSON Question

How to send a HTTP POST like this in Swift?

{
"appId":"YOUR_APP_ID",
"appKey":"YOU_APP_KEY",
"queries":{
"item_name":"Kids Fries",
"brand_name":"McDonalds"
}
}


I know how to handle the first two items(appId,appKey) in postString, but I don't know what the format be for "queries", I tried the following, it did not work:

let request = NSMutableURLRequest(URL: url! )
request.HTTPMethod = "POST"
let postString = "appId=myId9&appKey=myKey&queries={item_name=burger&brand_name=McDonalds}"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

Answer

What Content-Type does the server expect?

You are showing application/json in the first part, but application/x-www-form-urlencoded in the second part.


If you need application/json, then

let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let postString = "{\"appId\":\"myId\", \"appKey\":\"myKey\", \"queries\":{\"item_name\":\"Kids Fries\", \"brand_name\":\"McDonalds\"}}"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

If you really need application/x-www-form-urlencoded, then some guessing is involved. Why not try using the dot-syntax.

let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let postString = "appId=myId&appKey=myKey&queries.item_name=burger&queries.brand_name=McDonalds"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
Comments