httpBody没有通过URLRequest传递JSON正文

时间:2019-05-08 17:31:02

标签: json swift urlrequest

我正在尝试使用包含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()

0 个答案:

没有答案