0

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"
      ]
    ]
4

1 回答 1

0

对于Swift4Swift5 POST 使用更好地发出请求:

components.queryItems = [
    URLQueryItem(name: "email", value: "example@gmail.com"),
    URLQueryItem(name: "token", value: "3909")
]

服务器还可以,语法也可以,但是,正如我所见,它取决于 Swift 的版本。

整个代码:

let url = URL(string: "https://server.../verify")!
var components = URLComponents(url: url, resolvingAgainstBaseURL: false)!
components.queryItems = [
    URLQueryItem(name: "email", value: "example@gmail.com"),
    URLQueryItem(name: "token", value: "3909")
]
let query = components.url!.query
var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)

request.httpMethod = "POST"
request.httpBody = Data(query!.utf8)

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error!)
  } else {
      let httpResponse = response as? HTTPURLResponse
      print("response: \(httpResponse!)")
      let str = String(data: data!, encoding: .utf8)
      print(str!)
  }
})

dataTask.resume()
于 2020-01-07T10:24:38.373 回答