Swift 2 JSON POST request [dictionary vs. String for HTTPBody of NSMutableURLRequest]

≡放荡痞女 提交于 2019-12-20 03:40:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!