在Swift中通过HTTP POST方法发送字典数据

时间:2017-10-11 07:07:29

标签: swift dictionary httprequest

我试图在字典中设置带有参数的HTTP发布请求,这是我的字典

let parameters    = [
                    ["name": "tag","value": "login"],
                    ["name": "email","value": "s@s.com"],
                    ["name": "password","value": "aaaa"]
                    ]

但我不知道如何在她的完整请求函数中访问它

    func data_request(_ url:String)
{
    let parameter = [
                    ["name": "tag","value": "login"],
                    ["name": "email","value": "s@s.com"],
                    ["name": "password","value": "aaaa"]
                    ]
    let url:NSURL = NSURL(string: url)!
    let session = URLSession.shared

    let request = NSMutableURLRequest(url: url as URL)
    request.httpMethod = "POST"

    let paramString = parameter?
    request.httpBody = paramString.data(using: String.Encoding.utf8)

    let task = session.dataTask(with: request as URLRequest) {
        (
        data, response, error) in

        guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else {
            print("error")
            return
        }

        if let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        {
            print(dataString)
        }
    }

    task.resume()

}

2 个答案:

答案 0 :(得分:0)

需要将字典转换为json字符串,如下所示:

let jsonData = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)

After that pass to the http.Body

// insert json data to the request

 request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

 request.HTTPBody = jsonData

let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
            if error != nil{
                print("Error -> \(error)")
                return
            }

            do {
                let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]

                print("Result -> \(result)")

            } catch {
                print("Error -> \(error)")
            }
        }

        task.resume()
        return task



    } catch {
        print(error)
    }

答案 1 :(得分:0)

您需要将Dictionary转换为Data并将其设置为httpBody 你可以这样解决

let paramData = try? JSONSerialization.data(withJSONObject: parameter, options: []) request.httpBody = paramData