Insomnia生成的Swift代码适用于 1 key和 1 value ,但对于 2+ keys , values总是报错。如何在Swift4 + 中将数组数组作为POST方法发送?
失眠代码:
let headers = [
"content-type": "multipart/form-data; boundary=---011000010111000001101001",
"accept": "application/json"
]
let parameters = [
[
"name": "email",
"value": "example@gmail.com"
],
[
"name": "token",
"value": "911"
]
]
let boundary = "---011000010111000001101001"
var body = ""
let error: NSError? = nil
do{
for param in parameters {
let paramName = param["name"]!
body += "--\(boundary)\r\n"
body += "Content-Disposition:form-data; name=\"\(paramName)\""
if let filename = param["fileName"] {
let contentType = param["content-type"]!
let fileContent = try String(contentsOfFile: filename, encoding: String.Encoding.utf8)
if (error != nil) {
print(error as Any)
}
body += "; filename=\"\(filename)\"\r\n"
body += "Content-Type: \(contentType)\r\n\r\n"
body += fileContent
} else if let paramValue = param["value"] {
body += "\r\n\r\n\(paramValue)"
}
}
} catch { print(error.localizedDescription) }
let request = NSMutableURLRequest(url: NSURL(string: "https://server.../verify")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
let postData = body.data(using: .utf8)
request.httpBody = postData!
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error as Any)
} else {
let httpResponse = response as? HTTPURLResponse
print("response: \(httpResponse!)")
let str = String(data: data!, encoding: .windowsCP1250)
print(str!)
}
})
dataTask.resume()
似乎根本没有将任何值传输到服务器,但是,对于 1 个值,根本没有问题:
let parameters = [
[
"name": "email",
"value": "example@gmail.com"
]
]