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


Answers:


409

在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 parameters: [String: Any] = [
    "id": 13,
    "name": "Jack & Jill"
]
request.httpBody = parameters.percentEncoded()

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, 
        let response = response as? HTTPURLResponse, 
        error == nil else {                                              // check for fundamental networking error
        print("error", error ?? "Unknown error")
        return
    }

    guard (200 ... 299) ~= response.statusCode else {                    // check for http errors
        print("statusCode should be 2xx, but is \(response.statusCode)")
        print("response = \(response)")
        return
    }

    let responseString = String(data: data, encoding: .utf8)
    print("responseString = \(responseString)")
}

task.resume()

哪里:

extension Dictionary {
    func percentEncoded() -> Data? {
        return map { key, value in
            let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
            let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
            return escapedKey + "=" + escapedValue
        }
        .joined(separator: "&")
        .data(using: .utf8)
    }
}

extension CharacterSet { 
    static let urlQueryValueAllowed: CharacterSet = {
        let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
        let subDelimitersToEncode = "!$&'()*+,;="

        var allowed = CharacterSet.urlQueryAllowed
        allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
        return allowed
    }()
}

这将检查基本的网络错误以及高级HTTP错误。这也可以正确地对查询的参数进行转义。

请注意,我使用的nameof Jack & Jill来说明的正确x-www-form-urlencoded结果name=Jack%20%26%20Jill,该结果是“百分比编码”的(即,空格替换为%20&值中的替换为%26)。


请参阅此答案的先前修订版,以获取Swift 2演绎版本。


7
仅供参考,如果您要执行实际请求(包括转义百分比,创建复杂请求,简化响应解析),请考虑使用AFNetworking作者的AlamoFire。但是,如果您只是想提出一个琐碎的POST请求,则可以使用上面的方法。
罗布

2
谢谢Rob,那正是我想要的!只不过是一个简单的POST。好答案!
angeant 2014年

1
在寻找了几个不同的解决方案几个小时之后,第3行和第4行挽救了我的生命,因为我无法终生使NSJSONSerialization.dataWithJSONObject正常工作!
Zork

1
@complexi-与其在$_POST文件名和文件名之间绘制连接,不如将其简化为:如果您输入的URL不正确,PHP脚本将根本不会运行。但是不一定总是必须包含文件名(例如,服务器可能正在执行URL路由或具有默认文件名)。在这种情况下,OP给我们提供了一个包含文件名的URL,因此我只使用了与他相同的URL。
罗布

1
URLSession在这方面,Alamofire没有更好,也没有更坏。所有网络API本质上都是异步的,应该也是如此。现在,如果您正在寻找其他优雅的方式来处理异步请求,则可以考虑将它们(URLSession请求或Alamofire的请求)包装在异步的自定义Operation子类中。或者,您可以使用一些Promise库,例如PromiseKit。
罗布

69

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

6
我的代码出现以下错误:“由于格式不正确,无法读取数据。”
applecrusher

我认为您收到的字符串格式的响应可以验证吗?
Suhit Patil

1
我认为此解决方案中的问题是,您将参数传递为json序列化,而Web服务将其作为formdata参数
Amr Angry

是的,在解决方案中,参数为json,请与服务器检查是否需要表单数据,然后更改内容类型,例如request.setValue(“ application / x-www-form-urlencoded”,forHTTPHeaderField:“ Content-Type”)
Suhit Patil's

对于多部分参数,请使用let boundaryConstant =“ --V2ymHFg03ehbqgZCaKO6jy--”; request.addvalue(“ multipart / form-data boundary =(boundaryConstant)”,forHTTPHeaderField:“ Content-Type”)
Suhit Patil

17

对于寻求在Swift 5中编码POST请求的简洁方法的任何人。

您无需手动添加百分比编码。使用URLComponents创建一个GET请求URL。然后使用query该URL的属性来正确获取转义百分比的查询字符串。

let url = URL(string: "https://example.com")!
var components = URLComponents(url: url, resolvingAgainstBaseURL: false)!

components.queryItems = [
    URLQueryItem(name: "key1", value: "NeedToEscape=And&"),
    URLQueryItem(name: "key2", value: "vålüé")
]

let query = components.url!.query

query会是一个正确转义字符串:

key1 = NeedToEscape%3DAnd%26&key2 = v%C3%A5l%C3%BC%C3%A9

现在,您可以创建一个请求并将查询用作HTTPBody:

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = Data(query.utf8)

现在,您可以发送请求。


各种实例之后,只有这个工程的斯威夫特5
阿列克

我豪宅了GET请求,但我想知道POST请求呢?如何将参数传递到httpBody或我需要它?
Mertalp Tasdelen

智能解决方案!感谢您分享@pointum。我确信Martalp不再需要答案了,但是对于其他阅读的人,上面的请求是POST。
Vlad Spreys

12

这是我在日志记录库中使用的方法: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)

1
什么是application/x-www-form-urlencoded你在设置?
蜂蜜

用于在请求正文@Honey中传递数据
Achraf

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

3
@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
可能需要为此Swift 3/4进行更新才能使用URLRequest
Adam Ware

2

这里的所有答案都使用JSON对象。这给我们$this->input->post() 的Codeigniter控制器方法带来了问题 。在CI_Controller无法直接读取JSON。我们使用这种方法无需JSON

fun postRequest(){
//Create url object
guard let url = URL(string: yourURL) else {return}

//Create the session object
let session = URLSession.shared

//Create the URLRequest object using the url object
var request = URLRequest(url: url)

//Set the request method. Important Do not set any other headers, like Content-Type
request.httpMethod = "POST" //set http method as POST

//Set parameters here. Replace with your own.
let postData = "param1_id=param1_value&param2_id=param2_value".data(using: .utf8)
request.httpBody = postData
}

//Create a task using the session object, to run and return completion handler
let webTask = session.dataTask(with: request, completionHandler: {data, response, error in
guard error == nil else {
print(error?.localizedDescription ?? "Response Error")
return
}
guard let serverData = data else {
print("server data error")
return
}
do {
if let requestJson = try JSONSerialization.jsonObject(with: serverData, options: .mutableContainers) as? [String: Any]{
print("Response: \(requestJson)")
}
} catch let responseError {
print("Serialisation in error in creating response body: \(responseError.localizedDescription)")
let message = String(bytes: serverData, encoding: .ascii)
print(message as Any)
}
})
//Run the task
webTask.resume()

现在你是CI_Controller将能够获得param1param2使用$this->input->post('param1'),并$this->input->post('param2')

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.