xcode Swift 中的 HTTP 请求和 swift3 中的 POST 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43779111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTTP Request in Swift with POST method in swift3
提问by mike kumawat
I'm trying to run a HTTP Request in Swift3, to POST 2 parameters to a URL.
我正在尝试在 Swift3 中运行 HTTP 请求,将 2 个参数发布到 URL。
Example:
例子:
Link:
关联:
http://test.tranzporthub.com/street45/customer_login.php
Params:
参数:
{
"user_id":"[email protected]",
"password":"123"
}
What is the simplest way to do that?
最简单的方法是什么?
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.
我什至不想阅读回复。我只想发送它以通过 PHP 文件对我的数据库执行更改。
回答by Atlas_Gondal
I guess, you are totally newbie but here is something that you can try in SWIFT 3:
我想,您完全是新手,但您可以在SWIFT 3 中尝试以下内容:
- Open info.plistfile (Double Click OR Right Click > Open As > Source Code)
Paste this code before closing
</dict>
and</plist>
tags:<key>NSAppTransportSecurity</key> <dict> <key>NSExceptionDomains</key> <dict> <key>tranzporthub.com</key> <dict> <!--Include to allow subdomains--> <key>NSIncludesSubdomains</key> <true/> <!--Include to allow HTTP requests--> <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key> <true/> <!--Include to specify minimum TLS version--> <key>NSTemporaryExceptionMinimumTLSVersion</key> <string>TLSv1.1</string> </dict> </dict>
Now Open your view Controller and paste this code where you want to make post request:
var request = URLRequest(url: URL(string: "http://test.tranzporthub.com/street45/customer_login.php")!) request.httpMethod = "POST" let postString = "[email protected]&password=123" request.httpBody = postString.data(using: .utf8) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error print("error=\(error)") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors print("statusCode should be 200, but is \(httpStatus.statusCode)") print("response = \(response)") } let responseString = String(data: data, encoding: .utf8) print("responseString = \(responseString)") } task.resume()
- 打开info.plist文件(双击或右键单击 > 打开为 > 源代码)
在关闭
</dict>
和</plist>
标记之前粘贴此代码:<key>NSAppTransportSecurity</key> <dict> <key>NSExceptionDomains</key> <dict> <key>tranzporthub.com</key> <dict> <!--Include to allow subdomains--> <key>NSIncludesSubdomains</key> <true/> <!--Include to allow HTTP requests--> <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key> <true/> <!--Include to specify minimum TLS version--> <key>NSTemporaryExceptionMinimumTLSVersion</key> <string>TLSv1.1</string> </dict> </dict>
现在打开您的视图控制器并将此代码粘贴到您要发布请求的位置:
var request = URLRequest(url: URL(string: "http://test.tranzporthub.com/street45/customer_login.php")!) request.httpMethod = "POST" let postString = "[email protected]&password=123" request.httpBody = postString.data(using: .utf8) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error print("error=\(error)") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors print("statusCode should be 200, but is \(httpStatus.statusCode)") print("response = \(response)") } let responseString = String(data: data, encoding: .utf8) print("responseString = \(responseString)") } task.resume()
NOTE: You can remove print statements if you don't need!
注意:如果不需要,可以删除打印语句!
Hope this helps! :)
希望这可以帮助!:)
回答by User558
@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()
}