iOS:设置httpBody属性时HTTP POST请求超时

时间:2016-11-03 02:08:11

标签: ios swift url nsurlsession nsurlrequest

以下代码基于this excellent SO answer for making POST requests on iOS。此代码尝试发出POST请求:

  

http://requestb.in/14090od1

如果httpBody对象的URLRequest属性没有值,或者该值只是空字符串,则请求有效。

但是,一旦将非空值分配给httpBody,请求就会超时。

任何人都知道为什么?

// Succeeds
let userOptions = ["url": "http://requestb.in/14090od1"]
userOptions["bodyString" : ""]
doPost(userOptions: userOptions)

// Fails
let userOptions = ["url": "http://requestb.in/14090od1"]
userOptions["bodyString" : "hi"]
doPost(userOptions: userOptions)


fileprivate func doPost(userOptions: [String:Any]) {
    // Get URL string
    let urlString = userOptions["url"] as? String ?? ""

    // If invalid URL, return early
    guard let url = URL(string: urlString) else {
        printError("Error in doPost: malformed URL")
        return
    }

    // If here, URL valid so execute request
    // Create request
    var request = URLRequest(url: url)

    // Add headers
    if let tHeaders = userOptions["headers"] as? [String:String] {
        for (key, value) in tHeaders {
            request.setValue(value, forHTTPHeaderField: key)
        }
    }

    // Add body data
    let bodyString = userOptions["bodyString"] as? String ?? ""
    request.httpBody = bodyString.data(using: .utf8)

    // Create data task
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        // If networking error, return early
        guard let data = data, let httpResponse = response as? HTTPURLResponse, error == nil else {
            printError("Error with network while executing POST request: \(error)")
            return
        }

        // Why, oh why, does it not reach here???
    }

    // Start data task
    print("Executing HTTP request: \(request)")
    task.resume()
}

1 个答案:

答案 0 :(得分:1)

如果您要执行POST请求,不仅要设置httpBody,还要将请求的httpMethod设置为POST }。

request.httpMethod = "POST"