为什么响应总是 { "detail" : "Unsupported media type " 文本/纯\ " in request." } 在 swift 中?



我在Django中创建了一个示例应用程序,它从应用程序中删除一个问题。并在使用POSTMAN时提供正确的输出。

class Questions(APIView):
def delete(self,request):
received_id = request.POST["id"]
print(received_id)
place = Question.objects.get(pk=received_id)
place.delete()
questions = Question.objects.all()
seriliazer = QuestionSerializer(questions,many = True)
return Response({'Orgs': seriliazer.data})

然而,当我试图从iOS应用程序实现它时,它返回{"detail"; "不支持的媒体类型"text/plain"在请求!"}

func deleteQuestion( id: Int){
guard let url  = URL(string: "http://127.0.0.1:8000/V1/API/questions/") else {
return
}
var request = URLRequest(url: url)
let postString = "id=15"
request.httpBody = postString.data(using: String.Encoding.utf8);
request.httpMethod = "DELETE"
URLSession.shared.dataTask(with: request) { data, response, error in
let str = String(decoding: data!, as: UTF8.self)
print(str)
if error == nil {
self.fetcOrganizatinData()
}
}.resume()
}

不能真正理解问题到底在哪里?

如果api期望Json,则您发送的正文不是Json,而是编码为纯文本。如果它应该是Json,你可以将主体字符串更改为Json格式,如:

“{”id”:15}”
// you may want to tell it what you’re sending
request.setValue("application/json", forHTTPHeaderField: "Accept-Encoding")

另一件事可能是请求缺少Accept-Encoding头,它告诉api你正在发送什么,而Content-Type是api通常发送的内容。

当我通过特定网关发送请求时,我经历过头部注入,这些请求并不总是正确的。如果标题不存在,沿途可以尝试帮助您并添加标题。这在过去给我带来了问题。我仍然不知道它发生在堆栈中的确切位置,但添加头文件解决了我的问题。

你可以添加这样的标题:

request.setValue("charset=utf-8", forHTTPHeaderField: "Accept-Encoding")

DELETE请求的主体将被忽略,我可以从实体主体是否允许HTTP DELETE请求中猜测?职位。因此,最好发送完整的URL或在header中发送,

所以我写了下面的函数

def delete(self,request):
received_id = request.headers['id']
place = Question.objects.get(pk=received_id)
place.delete()
return HttpResponse("DELETE view is working fine ")

迅速和

func deleteQuestion( id: Int){
guard let url  = URL(string: "http://127.0.0.1:8000/V1/API/questions/") else {
return
}
var request = URLRequest(url: url)
//let postString = "id=(id)"
// request.httpBody =  postString.data(using: String.Encoding.utf8);
request.httpMethod = "DELETE"
request.setValue("charset=utf-8", forHTTPHeaderField: "Accept-Encoding")
request.setValue("charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("(id)", forHTTPHeaderField: "id")
URLSession.shared.dataTask(with: request) { data, response, error in
let str = String(decoding: data!, as: UTF8.self)
print(str)
if error == nil {
self.fetcOrganizatinData()
}
}.resume()
}

在标题中添加Content-Typeapplication/json<<strong>原因/strong>这是因为邮差有一些默认的报头,通常是8。其中之一是Content-Typetext/plain通过写入"Content-Type": "application/json",我们可以覆盖该规则。当你想要像JSON一样传递数据时,就这样做。了解更多什么是默认的邮差我建议你阅读这份邮差的官方文件。我通过覆盖默认的Content-Type

解决了这个问题。

相关内容

最新更新