且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift3中使用POST方法的HTTP请求

更新时间:2023-02-21 09:32:08

 @IBAction func postAction(_ sender: Any) {
    let Url = String(format: "your url")
    guard let serviceUrl = URL(string: Url) else { return }
    //        let loginParams = String(format: LOGIN_PARAMETERS1, "test", "Hi World")
    let parameterDictionary = ["username" : "@kilo_laco", "tweet" : "Hi World"]
    var request = URLRequest(url: serviceUrl)
    request.httpMethod = "POST"
    request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) else {
        return
    }
    request.httpBody = httpBody

    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print(response)
        }
        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
            }catch {
                print(error)
            }
        }
        }.resume()


}