Swift 2 JSON POST request [dictionary vs. String f

2019-03-01 18:02发布

问题:

I have the following swift code that submits a POST request successfully.

let request = NSMutableURLRequest(URL: NSURL(string: url)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.HTTPBody = "foo=bar&baz=lee".dataUsingEncoding(NSUTF8StringEncoding)

let task = session.dataTaskWithRequest(request, completionHandler: completionHandler)

Instead of using query parameter like syntax, I'd like to use a dictionary, but when I do the following:

let request = NSMutableURLRequest(URL: NSURL(string: url)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(["foo":"bar", "lee":"baz"], options: [])

let task = session.dataTaskWithRequest(request, completionHandler: completionHandler)

(like what I've seen around), it seems to submits the request as if the body is empty.

My main question is: how do these syntaxes differ, and how do the resulting requests differ?

NOTE: Coming from JS, I'm testing the endpoint in a javascript environment (jquery.com's console) like the following, and it's working successfully:

$.ajax({
  url: url,
  method: 'POST',
  data: {
    foo: 'bar',
    baz: 'lee'
  }
});

回答1:

What @mrkbxt said. It's not a matter of how the syntax differs, but a matter of the different data types your sending with your request. UTF8 string encoded text is the default value for NSMutableURLRequest content type, which is why your first request works. To use a JSON in the body you have to switch the content type to use JSON.

Add the following to your request object so it accepts JSON:

request.setValue("application/json", forHTTPHeaderField: "Content-Type")