我正在尝试使用包含JSON的httpBody POST
进行呼叫。运行代码时,我得到Request JSON object for insert cannot be null.
。在PostMan中运行相同的URL和JSON正文时,它可以工作。当我删除JSON正文时,会出现相同的错误。
let headers = [
"authorization": "Basic " + base64EncodedCredential!,
"cache-control": "no-cache"
]
let jsonBody = ["short_description": "this is a test from Xcode",
"caller_id": "USERNAME",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit."]
let url = URL(string: "https://some url")
var request = URLRequest(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
do {
request.httpBody = try JSONSerialization.data(withJSONObject: jsonBody, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
// Make request
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: {
(data, response, error) in
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
let decoder = JSONDecoder()
do {
let serviceRequest = try decoder.decode(Incident.self, from: data!)
} catch {
print("Error: \(error)")
}
} else {
}
})
task.resume()