当我使用 PUT 方法点击 API 时,如何解析描述 ["detail":请求中不支持的媒体类型“”。]?

How to resolve a description ["detail": Unsupported media type "" in request.] when I hit API with PUT method?

我目前正在使用 SwiftUI 开发应用程序。

我想更新数据库中的一些数据,该数据命中了 Django REST Framework 从 ios 应用程序创建的端点。

当我尝试更新(PUT method)Django REST Framework 中可浏览页面中的一些数据时,它运行良好,我可以更新数据,但是当我尝试从 ios 应用程序,它运行不正常...

然后我在控制台中收到一些消息,如下所示:

The response code is 415
The request is: ["detail": Unsupported media type "" in request.]

我该如何解决这个问题?


这是 SwiftUI 中的一段代码:

 func makePutCall(
        pk the_pk:Int,
        field_name the_field_name:String,
        memo the_memo:String
    ) {
        let pk = the_pk
        let endpoint: String = "https://sample.com/api/info/\(pk)/"
        
        guard let url = URL(string: endpoint) else {
            print("Error: cannot create URL")
            return
        }
        var urlRequest = URLRequest(url: url)
        urlRequest.addValue("token xxxxxxxxxxxxxxxxxxx", forHTTPHeaderField: "authorization")
        urlRequest.httpMethod = "PUT"
        urlRequest.httpBody = "field_name=\(the_field_name)&memo=\(the_memo)".data(using: .utf8)
        let session = URLSession.shared
        let task = session.dataTask(with: urlRequest) {
            (data, response, error) in
            guard error == nil else {
                print("error calling PUT")
                print(error!)
                return
            }
            guard let responseData = data else {
                print("Error: did not receive data")
                return
            }
            guard let response = response as? HTTPURLResponse else {
                print("Error: did not response data")
                return
            }
            print("The response code is \(response.statusCode)")
            do {
                guard let receivedData = try JSONSerialization.jsonObject(with: responseData,
                                                                          options: []) as? [String: Any] else {
                    print("Could not get JSON from responseData as dictionary")
                    return
                }
                print("The request is: " + receivedData.description)
                
            } catch  {
                print("error parsing response from PUT")
                return
            }
        }
        task.resume()
    }

已更新:

我尝试添加一些代码来设置 Content-Type,如下所示,然后错误消息发生了变化,但我仍然无法更新一些数据...

  ...
  var urlRequest = URLRequest(url: url)
  urlRequest.addValue("token xxxxxxxxxxxxxxxx", forHTTPHeaderField: "authorization")
  urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") //←I added this line
  urlRequest.httpMethod = "PUT"
  ...

以下是按摩:

The response code is 400
The request is: ["detail": JSON parse error - Expecting value: line 1 column 1 (char 0)]

Xcode:版本 12.0.1

DjangoRESTframework: 3.12.1

Django:3.1.2

您发送的数据未正确格式化为 json 对象,这会导致错误。请尝试找出您在请求中发送的数据中的语法错误。

尝试输出您在 PUT 请求中发送的值。确保它遵循 JSON 格式,并且 JSON 数据中没有尾随逗号。