我正在尝试将JSON正文发送到REST API,但它仅读取第一个参数,而根本无法识别JSON的其余部分。我测试了JSON正文其他部分的错误,但没有像往常一样收到错误。
func postRequest(classroomID: String, email: String, vote: String){
//declare parameter as a dictionary which contains string as key and value combination.
let parameters = [
"classroomID": classroomID,
"LastUpdated": "2020-01-01",
"TheVoteData"[
"Email": email,
"TheVote": vote
]
]
//create the url with NSURL
let url = URL(string: "https://www.api-gateway/dynamoDB/resource")!
//create the session object
let session = URLSession.shared
//now create the Request object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to data object and set it as request body
} catch let error {
print(error.localizedDescription)
}
//HTTP Headers
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request, completionHandler: { data, response, error in
guard error == nil else {
completion(nil, error)
return
}
guard let data = data else {
return
}
do {
//create json object from data
guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] else {
return
}
print(json)
completion(json, nil)
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
}
这会将教室ID发布到数据库,但不会通过电子邮件或投票发布。我从这里得到这种方法:How to make HTTP Post request with JSON body in Swift
非常感谢您的帮助!
我认为您在参数中提供的JSON数据无效(我使用jsonlint.com进行检查),尝试以下操作:
没有看到您的API代码,您可以尝试使用URLQueryItems(它们也更安全):