簡體   English   中英

快速發送POST請求,但收到405響應(不允許該方法)

[英]Sending a POST request in swift but getting a 405 response (method not allowed)

我向API發出POST請求。 我已經使用Postman和其他第三方工具測試了API,並且Im得到了200條響應。 但是,當我從swift發出請求時,我得到405響應(不允許使用該方法),並且顯示一條錯誤消息,指出即使明顯是在發出POST請求,也不允許“ GET”請求。

我已經檢查了肯定包含數據的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(configuration: URLSessionConfiguration.default)

代替

URLSession.shared

我遇到了同樣的問題,這對我有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM