Swift Post Request - JSON Body为空

时间:2018-06-19 08:08:43

标签: ios json swift rest api

我正在尝试基于REST服务器API执行POST请求。

每次执行代码时,服务器都不会收到发送的正文。 服务器收到如下所示的正文:{}

请求中使用的结构如下所示:

struct CreateUser: Codable {
   let first_name: String
   let email: String
   let password: String
}

请求按如下方式完成:

let userToRegister = CreateUser(firstName: "Max", email: "max.mustermann@gmail.com", password: "SECRET_PASSWORD")
let str = API_ENDPOINT
var request : URLRequest = URLRequest(url: URL(string: str)!)
let encoder = JSONEncoder()
let jsonData = try? encoder.encode(userToRegister)
request.httpBody = jsonData
request.httpMethod = "POST"
return URLSession.shared.dataTask(with: request, completionHandler: {(data,response,error) in
    DispatchQueue.main.async {
        if let httpResponse = response as? HTTPURLResponse {
            if httpResponse.statusCode == 200 {
                //Code for successful request
            } else {
                //Code for failure in request
            }
        }
    }
})

1 个答案:

答案 0 :(得分:1)

我已经解决了这个问题。您必须添加以下行:

request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")