HTTP Request in Swift with POST method

前端 未结 7 1009
名媛妹妹
名媛妹妹 2020-11-22 05:46

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

Example:

Link: www.thisismylink.com/postName.php

Params:

7条回答
  •  时光取名叫无心
    2020-11-22 06:13

    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")
            }
    

提交回复
热议问题