HTTP Request in Swift with POST method

前端 未结 7 1045
名媛妹妹
名媛妹妹 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:22

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

提交回复
热议问题