我有POST请求:
init (url: String,arg: String) {
self.responseString = nil
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
let postString = arg
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) {
data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
self.responseString = nil
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { //
self.responseString = nil
} else {
self.responseString = String(data: data, encoding: .utf8)
}
}
task.resume()
}
当arg有一个字符\ n时,会丢失一半的arg文本。怎么解决这个问题?
答案 0 :(得分:1)
strUrl = strUrl.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
let url = URL.init(string: strUrl)
let requestURL = URLRequest(url: url!)