1. 程式人生 > >【iOS】(swift)AFNetworking3傳x-www-form-urlencode資料

【iOS】(swift)AFNetworking3傳x-www-form-urlencode資料

使用AFNetworking框架傳x-www-form-urlencode資料伺服器一直返回引數不存在的錯誤。

let manager = AFHTTPSessionManager()
manager.requestSerializer = AFHTTPRequestSerializer()
manager.requestSerializer.setValue(token, forHTTPHeaderField: "Authorization")
manager.requestSerializer.setValue("5", forHTTPHeaderField: "beId"
) manager.requestSerializer.setValue("application/x-www-form-urlencode", forHTTPHeaderField: "Content-Type") manager.post(url, parameters: dict, progress: nil, success: { task, responseObject in if let anObject = responseObject { print("上傳成功 === \(anObject)") } }, failure: { task, error in
print("上傳錯誤 == error == \(error)") })

看了這篇https://stackoverflow.com/questions/35239506/afnetworking-3-x-www-form-urlencoded-post-data才找到解決的辦法。
這裡寫圖片描述
對比之後發現他沒加manager.requestSerializer.setValue("application/x-www-form-urlencode", forHTTPHeaderField: "Content-Type")這句程式碼,試著去掉果然能正常返回。
修改後完整程式碼:

let manager = AFHTTPSessionManager()
manager.requestSerializer
= AFHTTPRequestSerializer() manager.requestSerializer.setValue(token, forHTTPHeaderField: "Authorization") manager.requestSerializer.setValue("5", forHTTPHeaderField: "beId") // manager.requestSerializer.setValue("application/x-www-form-urlencode", forHTTPHeaderField: "Content-Type") manager.post(url, parameters: dict, progress: nil, success: { task, responseObject in if let anObject = responseObject { print("上傳成功 === \(anObject)") } }, failure: { task, error in print("上傳錯誤 == error == \(error)") })

想要post x-www-form-urlencode資料反而不能加請求頭宣告Content-Type為x-www-form-urlencode。