Search code examples
swiftnsurlsessionhttp-status-code-400

Status code 400 while making POST request in swift


I keep getting this error which I don't know how to resolve! I'm trying to parse access token from a web API and for that I've set up post request. Somehow it's throwing an error on 'responseString' line.

import UIKit
import Foundation

class ViewController: UIViewController, NSURLConnectionDelegate {

    @IBOutlet var userName: UITextField!
    @IBOutlet var password: UITextField!

    @IBAction func submit(sender: AnyObject) {

        let postString = "username=" + userName.text + "&password=" + password.text + "&grant_type=password";
        let data: NSData = postString.dataUsingEncoding(NSUTF8StringEncoding)!
        let base64LoginString = data.base64EncodedStringWithOptions(nil)
        let postLength=NSString(format: "%ld", data.length)

        let url = NSURL(string: "http://www.myurl.com/Token")
        let request = NSMutableURLRequest(URL: url!);
        request.HTTPMethod = "POST"
        request.HTTPBody = data
        request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.addValue(base64LoginString, forHTTPHeaderField: "Authorization")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {data, response, error in

            if error != nil {
            println("error = \(error)")
            return

            }
        //print out response object
            println("******* response = \(response)")

        //print out response body // THIS LINE THROWS STATUS CODE 400 ERROR
            let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("******* response data = \(responseString)")

            var err: NSError?
            var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary

            if let parseJSON = json {
                var token = parseJSON["access_token"] as? String
                println("token: \(token)")

            }

        }


        task.resume()

    }

This is the error

******* response = <NSHTTPURLResponse: 0x7ff1eb4496d0> { URL: https://www.myurl.com/Token } { status code: 400, headers {
    "Cache-Control" = "no-cache";
    "Content-Length" = 34;
    "Content-Type" = "application/json;charset=UTF-8";
    Date = "Mon, 10 Aug 2015 20:16:14 GMT";
    Expires = "-1";
    Pragma = "no-cache";
    "X-Powered-By" = "ASP.NET";
} }

Solution

  • Your error seems to be incorrect usage of basic auth format. It should be like this:

    Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

    where

    QWxhZGRpbjpvcGVuIHNlc2FtZQ==

    is username:password in base64

    So in your case it is like this :

        let postString = userName.text + ":" + password.text ;
        let data: NSData = postString.dataUsingEncoding(NSUTF8StringEncoding)!
        let base64LoginString = data.base64EncodedStringWithOptions(nil)
        let postLength=NSString(format: "%ld", data.length)
    
        let url = NSURL(string: "http://www.myurl.com/Token")
        let request = NSMutableURLRequest(URL: url!);
        request.HTTPMethod = "POST"
        request.HTTPBody = ""
        request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.addValue("Basic " + base64LoginString, forHTTPHeaderField: "Authorization")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.setValue("0", forHTTPHeaderField: "Content-Length")
    

    btw it would be a lot easier to find your error if you provide your api url