ArseanlFC
ArseanlFC

Reputation: 1

Differences between Using NSJSONSerialization.dataWithJSONObject and dataUsingEncoding to make up the HTTP body in Swift

I have seen two kinds of methods to make up the HTTP body.
First one is:

let url = NSURL(string: "http://example.com")  
let request = NSMutableURLRequest(URL: url!)  
request.HTTPMethod = "POST"  
let postString = "id=13&name=Jack"  
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)  

Second one is:

let url = NSURL(string: "http://example.com")  
let request = NSMutableURLRequest(URL: url!)  
request.HTTPMethod = "POST"  
let params = ["id":"13", "name":"Jack"] as Dictionary<String, String>
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)

When I directly print out the request.HTTPBody the data is different. So I am wondering are there any differences between these two methods in terms of the implementation of the server side? Assuming I'am using PHP.

Upvotes: 0

Views: 296

Answers (1)

larva
larva

Reputation: 5148

there're two format data.

in code using postString.dataUsingEncoding it will send data in urlencoded format. In client you must set request's Content-Type header to "application/x-www-form-urlencoded" or something like "application/x-www-form-urlencoded charset=utf-8"

in code using NSJSONSerialization.dataWithJSONObject it will send data in json format. In client you must set request's Content-Type header field to "application/json"

I'm iOS dev so I don't know about format's effect to server side PHP. to answer your question you must find difference between application/x-www-form-urlencoded and application/json format in server side

Upvotes: 1

Related Questions