问题
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")
回答2:
For a content-Type of type "x-www-form-urlencoded" you can do the following.
let bodyParameter = ["foo":"bar", "lee":"baz"]
let bodyString = bodyData.map { "\($0)=\($1)" }.joined(separator: "&")
let encodedData = NSMutableData(data: bodyString.data(using: String.Encoding.utf8)!)
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.HTTPBody
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let task = session.dataTaskWithRequest(request, completionHandler: completionHandler)
This will take your dictionary, tranform it into a string that conforms to the content-Type of your request (by joining the dictionary using a separator) and then encoding it using utf8.
来源:https://stackoverflow.com/questions/36704965/swift-2-json-post-request-dictionary-vs-string-for-httpbody-of-nsmutableurlreq