我需要发出一个post请求,在post请求的正文中发送一个需要用utf-8编码的字典,我在下面尝试了这个,但它给出了一个错误:
let DicObject: NSMutableDictionary = NSMutableDictionary()
DicObject.setValue("cf", forKey: "a")
DicObject.setValue("", forKey: "scs")
DicObject.setValue("Uploads/" + nameOfFile, forKey:"p")
当我尝试制作时
request.httpMethod = "POST"
// request.httpBody = jsonObject as Data
request.addValue("Content-Type", forHTTPHeaderField: "application/x-www-form-urlencoded; charset=utf-8")
它不起作用,有人知道如何将jsonObject
编码转换为utf-8 吗
谢谢。
您可以使用JSONSerialization
将jsonObject
转换为data
if let data = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
request.httpBody = data
}
试试这个,
let jsonData: NSData
do {
jsonData = try JSONSerialization.data(withJSONObject: DicObject, options: JSONSerialization.WritingOptions()) as NSData
let jsonString = NSString(data: jsonData as Data, encoding: String.Encoding.utf8.rawValue)! as String
print("json string = (jsonString)")
print("json jsonData = (jsonData)")
} catch _ {
print ("JSON Failure")
}
谢谢!
您可以使用此Alamofire方法
mydict = [:] // Your parameters here
if let theJSONData = try? JSONSerialization.data(
withJSONObject: mydict,
options: []) {
let theJSONText = String(data: theJSONData,
encoding: .ascii)
multipartFormData.append((theJSONText?.data(using: .utf8)!)!, withName: "bulkData")
}