Swift中的HTTP请求以及swift3中的POST方法 [英] HTTP Request in Swift with POST method in swift3

查看:645
本文介绍了Swift中的HTTP请求以及swift3中的POST方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Swift3中运行HTTP请求,以将2个参数发布到URL。

I'm trying to run a HTTP Request in Swift3, to POST 2 parameters to a URL.

示例:

链接:

http://test.tranzporthub.com/street45/customer_login.php

参数:

{
    "user_id":"chaitanya3191@gmail.com",
    "password":"123"
}

最简单的方法是什么?

我什至不想阅读响应。我只想发送该文件,以通过PHP文件对数据库进行更改。

I don't even want to read the response. I just want to send that to perform changes on my database through a PHP file.

推荐答案

 @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()


}

这篇关于Swift中的HTTP请求以及swift3中的POST方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆