简体   繁体   English

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

[英]HTTP Request with Body using PATCH in Swift

I'm trying to send a Patch request with a serialized JSON Body.我正在尝试使用序列化的 JSON 正文发送 Patch 请求。

For some reason the server is not able to receive the body properly.由于某种原因,服务器无法正确接收正文。 I have a feeling that there seems to be a problem with the PATCH method in combination with the http request body.我有一种感觉,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()

You could try to add a Content-Type header to the request:您可以尝试向请求添加 Content-Type 标头:

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

or use one of the other JSON Content-Type formats described here .或使用此处描述的其他 JSON Content-Type 格式之一。

I tested it with an ExpressJS server and without the Content-Type header the server got an empty body, but with a Content-Type header it worked well.我使用 ExpressJS 服务器对其进行了测试,如果没有 Content-Type 标头,服务器的正文为空,但是使用 Content-Type 标头它运行良好。

in swift 3/4 :迅速 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()

Simple Way to use PATCH WITHOUT USING HTTPBody不使用 HTTPBody 使用 PATCH 的简单方法

if you want to just use PATCH than you can do it also such as following如果您只想使用 PATCH,那么您也可以这样做,例如以下

for an example, you just want to change the value of the name of a specific user then it will be like:-例如,您只想更改特定用户名称的值,然后它将类似于:-

let myurl = URL(string: "https://gorest.co.in/public-api/users/"+"(id)?"+"name=abc")!让 myurl = URL(string: "https://gorest.co.in/public-api/users/"+"(id)?"+"name=abc")!

var request = URLRequest(url:myurl) var request = URLRequest(url:myurl)

request.addValue("Bearer yourAuthorizationToken",forHTTPHeaderField:"Authorization") request.addValue("Bearer yourAuthorizationToken",forHTTPHeaderField:"Authorization")

request.httpMethod = "PATCH" request.httpMethod = "补丁"

let dataTask = URLSession.shared.dataTask(with: request) dataTask.resume()让 dataTask = URLSession.shared.dataTask(with: request) dataTask.resume()

Note:- here "id" will be userId注意:- 这里的“id”将是 userId

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM