Swift3中使用POST方法的HTTP请求 [英] HTTP Request in Swift with POST method in swift3
本文介绍了Swift3中使用POST方法的HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 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()
}
这篇关于Swift3中使用POST方法的HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文