这是我要向服务器发送请求的操作。
let urlStr = "someurl"
var request = URLRequest(url: URL(string: urlStr)!)
request.addValue(accessToken!, forHTTPHeaderField: "accessToken")
let postString = self.makeRequestString(dict: paramDict)
request.httpMethod = "POST"
request.httpBody = postString.data(using: .utf8, allowLossyConversion: true)
let session = URLSession.shared
request.timeoutInterval = 60
let task = session.dataTask(with: request) { data, response, error in
}
这是makeRequestString
的方法描述func makeRequestString(dict:Dictionary<String,AnyObject>) -> String {
let data = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
let str = String(data: data!, encoding: .utf8)
return "key=" + str!
}
我面临的问题是,如果我的字典参数中包含一些特殊字符,例如!@#$%^&amp; (),那么服务器不接受请求并给出一些不良结果。
我在错过任何错误代码的任何建议或指示。
修改
现在,如果我在方法 makeRequestString
中更改以下代码行,我会从服务器获得所需的响应 let str = String(data: data!, encoding: .utf8)?.replacingOccurrences(of: "&", with: "%26")
答案 0 :(得分:0)
尝试使用此编码:
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)!