我正在向 API 发出 POST 请求。我已经使用 Postman 和另一个第三方工具测试了 API,并且收到了 200 响应。但是,当我从 swift 发出请求时,我收到 405 响应(不允许使用方法)和一条错误消息,指出不允许“GET”请求,即使我显然正在发出 POST 请求。
我已经检查了 httpBody,它肯定包含数据。我只是不明白我在这里做错了什么。这是我的代码:
let json : [Dictionary<String,Any>] = [["label" : "Misc", "ignored": true], ["label" : "Cash", "ignored": false]]
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = try? JSONSerialization.data(withJSONObject: json)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let response = response {
print(response)
}
}
task.resume()
最佳答案
尝试使用
URLSession(配置:URLSessionConfiguration.default)
而不是
URLSession.shared
我遇到了同样的问题,这对我有用。
关于ios - 快速发送 POST 请求但收到 405 响应(不允许的方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52813843/