3

I'm trying to send a Patch request with a serialized JSON Body.

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.

    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()
DamirDiz
  • 691
  • 2
  • 9
  • 15

3 Answers3

3

You could try to add a Content-Type header to the request:

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

or use one of the other JSON Content-Type formats described here.

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.

Community
  • 1
  • 1
linath
  • 96
  • 3
3

in 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()
Osman
  • 1,040
  • 12
  • 19
1

Simple Way to use PATCH WITHOUT USING HTTPBody

if you want to just use PATCH than you can do it also such as following

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")!

var request = URLRequest(url:myurl)

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

request.httpMethod = "PATCH"

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

Note:- here "id" will be userId