Translating Alamofire call to URLSession
<p>I've got a old codebase that I'm trying to migrate out of. The network calls currently use Alamofire 4.0 and I'm trying to use <code>URLSession</code> instead. I'm having trouble figuring out what's wrong, here's what I've been doing. I start off with the route and params that I want to post:</p>

<pre><code>// route to user creation
let url = ...

let params = ["user": ["first_name": "John", "last_name": "Appleseed", "email": "john@apple.com", "password": "asdfgh"]]
</code></pre>

<p>Here's the old and new network calls:</p>

<pre><code>// old network request
Alamofire.request(url, method: .post, parameters: newUser, encoding: JSONEncoding.default).responseJSON { response in
  // ...
}

// new code
var request = URLRequest(url: url)
let jsonData = try! JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
request.httpBody = jsonData
request.httpMethod = "POST"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
  guard let data = data, error == nil else { return print("error=\(error)") }

  if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
    print("status code should be 200, but is \(httpStatus.statusCode)")
    print("response = \(response)")
  }

  let responseString = String(data: data, encoding: .utf8)
  print("responseString = \(responseString)")
}

task.resume()
</code></pre>

<p>For some reason, I'm getting a status code of 400 in my <code>URLSession</code> attempt. Alamofire works fine.</p>

<p>Any advice appreciated.</p>