Django rest framework 当我使用PUT方法点击API时,如何解析描述[“详细信息”:请求中的“不支持的媒体类型”]?
我目前正在使用SwiftUI开发一个应用程序 我想更新一个数据库中的一些数据,该数据库访问由ios应用程序中的Django REST Framework生成的端点 当我尝试在Django REST框架中更新(Django rest framework 当我使用PUT方法点击API时,如何解析描述[“详细信息”:请求中的“不支持的媒体类型”]?,django-rest-framework,swift5,Django Rest Framework,Swift5,我目前正在使用SwiftUI开发一个应用程序 我想更新一个数据库中的一些数据,该数据库访问由ios应用程序中的Django REST Framework生成的端点 当我尝试在Django REST框架中更新(PUT method)可浏览页面中的一些数据时,它工作得很好,我可以更新数据,但当我尝试在ios应用程序中执行相同的操作时,它不工作得很好 然后我在控制台中收到一些消息,如下所示: The response code is 415 The request is: ["detail&
PUT method
)可浏览页面中的一些数据时,它工作得很好,我可以更新数据,但当我尝试在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()
}
已更新: 我试图添加一些代码来设置
内容类型
,如下所示,然后错误消息已更改,但我仍然无法更新某些数据
...
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版 Djangorest框架:3.12.1
Django:3.1.2您发送的数据未正确格式化为json对象,这会导致错误。请尝试在请求中发送的数据中查找语法错误。尝试输出请求中发送的值。确保它遵循JSON格式,并且JSON数据中没有尾随逗号。我将HTTP正文更改为数组数据,然后它就可以正常工作了。