首页 文章

使用POST方法在Swift中进行HTTP请求

提问于
浏览
137

我正在尝试在Swift中运行HTTP请求,将POST 2参数发送到URL .

例:

链接: www.thisismylink.com/postName.php

PARAMS:

id = 13
name = Jack

最简单的方法是什么?

我甚至不想阅读回复 . 我只是想发送它来通过PHP文件对我的数据库进行更改 .

5 回答

  • 333

    在Swift 3中,您可以:

    let url = URL(string: "http://www.thisismylink.com/postName.php")!
    var request = URLRequest(url: url)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    let postString = "id=13&name=Jack"
    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()
    

    这将检查基本网络错误以及高级HTTP错误 .

    有关Swift 2的再现,请参阅previous revision of this answer .

  • 2

    Swift 3 and swift 4

    @IBAction func submitAction(sender: UIButton) {
    
        //declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid
    
        let parameters = ["id": 13, "name": "jack"]
    
        //create the url with URL
        let url = URL(string: "www.thisismylink.com/postName.php")! //change the url
    
        //create the session object
        let session = URLSession.shared
    
        //now create the URLRequest object using the url object
        var request = URLRequest(url: url)
        request.httpMethod = "POST" //set http method as POST
    
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
        } catch let error {
            print(error.localizedDescription)
        }
    
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
    
        //create dataTask using the session object to send data to the server
        let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
    
            guard error == nil else {
                return
            }
    
            guard let data = data else {
                return
            }
    
            do {
                //create json object from data
                if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                    print(json)
                    // handle json...
                }
            } catch let error {
                print(error.localizedDescription)
            }
        })
        task.resume()
    }
    
  • 31

    下面是我在日志库中使用的方法:https://github.com/goktugyil/QorumLogs

    此方法填写Google表单中的html表单 .

    var url = NSURL(string: urlstring)
    
        var request = NSMutableURLRequest(URL: url!)
        request.HTTPMethod = "POST"
        request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding)
        var connection = NSURLConnection(request: request, delegate: nil, startImmediately: true)
    
  • 8
    @IBAction func btn_LogIn(sender: AnyObject) {
    
        let request = NSMutableURLRequest(URL: NSURL(string: "http://demo.hackerkernel.com/ios_api/login.php")!)
        request.HTTPMethod = "POST"
        let postString = "email: test@test.com & password: testtest"
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request){data, response, error in
            guard error == nil && data != nil else{
                print("error")
                return
            }
            if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200{
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            }
            let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
            print("responseString = \(responseString)")
        }
        task.resume()
    }
    
  • 1
    let session = URLSession.shared
            let url = "http://...."
            let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
            request.httpMethod = "POST"
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            var params :[String: Any]?
            params = ["Some_ID" : "111", "REQUEST" : "SOME_API_NAME"]
            do{
                request.httpBody = try JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions())
                let task = session.dataTask(with: request as URLRequest as URLRequest, completionHandler: {(data, response, error) in
                    if let response = response {
                        let nsHTTPResponse = response as! HTTPURLResponse
                        let statusCode = nsHTTPResponse.statusCode
                        print ("status code = \(statusCode)")
                    }
                    if let error = error {
                        print ("\(error)")
                    }
                    if let data = data {
                        do{
                            let jsonResponse = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions())
                            print ("data = \(jsonResponse)")
                        }catch _ {
                            print ("OOps not good JSON formatted response")
                        }
                    }
                })
                task.resume()
            }catch _ {
                print ("Oops something happened buddy")
            }
    

相关问题