带有Body的HTTP请求在Swift中使用PATCH

时间:2015-07-03 10:40:58

标签: ios swift rest http patch

我正在尝试使用序列化的JSON Body发送Patch请求。

由于某种原因,服务器无法正常接收身体。我觉得PATCH方法与http请求体一起出现了问题。

    let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)

    var URL = B2MFetcher.urlForBooking(event.unique, bookingID: booking.unique)
    let request = NSMutableURLRequest(URL: URL)
    request.HTTPMethod = "PATCH"

    // Headers
    println(token)
    request.addValue(token, forHTTPHeaderField: "Authorization")
    request.addValue("gzip, identity", forHTTPHeaderField: "Accept-Encoding")

    // JSON Body
    let bodyObject = [
        "op": "cancel"
    ]
    var jsonError: NSError?
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(bodyObject, options: nil, error: &jsonError)

    /* Start a new Task */
    let task = session.dataTaskWithRequest(request, completionHandler: { (data : NSData!, response : NSURLResponse!, error : NSError!) -> Void in
        completion(data: data, response:response , error: error)
    })
    task.resume()

3 个答案:

答案 0 :(得分:2)

您可以尝试在请求中添加Content-Type标头:

request.addValue("application/json", forHTTPHeaderField: "Content-Type")

或使用this Travis CI Google Group thread所述的其他JSON内容类型格式之一。

我使用ExpressJS服务器测试它,没有Content-Type标头,服务器得到一个空体,但是使用Content-Type标头它运行良好。

答案 1 :(得分:1)

在swift 3/4中:

 let request = NSMutableURLRequest(url: NSURL(string: "http://XXX/xx/xxx/xx")! as URL)
        request.httpMethod = "PATCH"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        do{

           let json: [String: Any] = ["status": "test"]
           let jsonData = try? JSONSerialization.data(withJSONObject: json)
            request.httpBody = jsonData
            print("jsonData: ", String(data: request.httpBody!, encoding: .utf8) ?? "no body data")
        } catch {
            print("ERROR")
        }

        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in

            if error != nil {
                print("error=\(error)")
                completion(false)
                return
            }

            let responseString = NSString(data: data!, encoding:            String.Encoding.utf8.rawValue)
            print("responseString = \(responseString)")
            completion(true)
            return
        }
        task.resume()

答案 2 :(得分:1)

无需使用HTTPBody即可使用PATCH的简单方法

如果您只想使用PATCH,也可以执行以下操作,例如

例如,您只想更改特定用户名的值,则它将像:-

let myurl = URL(字符串:“ https://gorest.co.in/public-api/users/” +“(id)?” +“ name = abc”)!

var request = URLRequest(url:myurl)

request.addValue(“ Bearer yourAuthorizationToken”,forHTTPHeaderField:“ Authorization”)

request.httpMethod =“ PATCH”

let dataTask = URLSession.shared.dataTask(带有:request) dataTask.resume()

注意:-这里的“ id”将是userId