Dominic Jordan
Dominic Jordan

Reputation: 65

HTTP Request works by Postman but not in Swift

I am working on a simple app that has to login onto the website of our university and return the saldo on my card to me.

When I perform this simple request with postman it works fine and I get the logged in HTML page. Performing the same request on XCODE doesn't work:

override func viewDidLoad() {
    super.viewDidLoad()


    var dataString = "j_username=USERNAME&j_password=PASSWORD"
    var request : NSMutableURLRequest = NSMutableURLRequest()
    request.URL = NSURL(string: "https://campuscard.hhs.nl/portal/j_spring_security_check")
    var postString = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
    request.HTTPMethod = "POST"
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    //request.setValue("JSESSIONID=C78C688403A836968EC1FEAED9AE9126", forHTTPHeaderField: "Cookie")
    //request.setValue("campuscard.hhs.nl", forHTTPHeaderField: "Host");
    request.setValue("keep-alive", forHTTPHeaderField: "Connection");
    request.setValue("41", forHTTPHeaderField: "Content-Length");
    //request.setValue("max-age=0", forHTTPHeaderField: "Cache-Controle");
    //request.setValue("*/*", forHTTPHeaderField: "Accept");
    //request.setValue("https://campuscard.hhs.nl", forHTTPHeaderField: "Origin");
    //request.setValue("https://campuscard.hhs.nl/portal/login", forHTTPHeaderField: "Referer");
    //request.setValue("gzip,deflate", forHTTPHeaderField: "Accept-Encoding");
    //request.setValue("nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4", forHTTPHeaderField: "Accept-Language");
    request.HTTPBody = postString
    println(request);
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
        println(NSString(data: data, encoding: NSUTF8StringEncoding))
    }
}

The page won't login... The printed request looks like:

<NSMutableURLRequest: 0x7fecdb54b720> { URL: https://campuscard.hhs.nl/portal/j_spring_security_check, headers: {
    Accept = "*/*";
    "Accept-Encoding" = "gzip,deflate";
    "Accept-Language" = "nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4";
    "Cache-Controle" = "max-age=0";
    Connection = "keep-alive";
    "Content-Length" = 41;
    "Content-Type" = "application/x-www-form-urlencoded";
} }

Does anybody know what the difference is between the request that postman sends, and the request that I perform?

Thanks in advance!

Upvotes: 0

Views: 1788

Answers (1)

Dominic Jordan
Dominic Jordan

Reputation: 65

In this special occasion a security token had to be sent in the request too. I solved this by monitoring the request closely within the Google Chrome debugger.

Upvotes: 2

Related Questions