Adrien
Adrien

Reputation: 2206

POST body request is badly built using NSJSONSerialization.dataWithJSONObject

I am trying to create POST requests using NSMutableURLRequest but passing a NSData object to its HTTPBody does not behave as expected.

Here is what I do:

    guard let url = NSURL(string: endpoint) else {
        print("Error: Cannot create URL")
        return nil
    }
    do {
        let params = try NSJSONSerialization.dataWithJSONObject(options, options: [])

        let urlRequest:NSMutableURLRequest = NSMutableURLRequest(URL: url)
        urlRequest.HTTPMethod = method

        if method != "GET" {
            urlRequest.HTTPBody = params
        }

        return urlRequest

    } catch {
        print("Error: Cannot parse options data into JSON")
        return nil
    }

Here is what I get:

#<Hashie::Mash {"token":"MVgutecI0y5AzJ8KcIgkxT56mwEh","email":"[email protected]","password":"adichris"}=nil>

My server is written in Ruby. Here is how I fetch it:

puts params.inspect

Upvotes: 1

Views: 63

Answers (1)

Marcio
Marcio

Reputation: 2107

Since you are posting JSON you must set the request's Content-Type header to application/json before returning it.

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

Upvotes: 3

Related Questions