Veeru Veeru - 4 months ago 10
Swift Question

How to POST NSMutableURLRequest alogn with custome header fields using Alamofire

I'm trying POST NSMutableURLRequest request through Alamofire, but not able to set these filed value in HTTP header. Any help ?

var params = ["username":"veeru@gamil.com", "password":"Pasword123!", "csrfmiddlewaretoken":csrfToken] as Dictionary<String, String>

var post:NSString = "csrfmiddlewaretoken=Basic \(csrfToken)&username=veeru@gmail.com&password=Password123!"
var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!

var URL = NSURL(string: "https://myurl/account/login")
var mutableURLRequest = NSMutableURLRequest(URL: URL!)
mutableURLRequest.setValue("Content-Type", forHTTPHeaderField: "application/x-www-form-urlencoded")
mutableURLRequest.setValue("keep-alive", forHTTPHeaderField: "Connection")
mutableURLRequest.setValue("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36", forHTTPHeaderField: "User-Agent")
mutableURLRequest.setValue("Code", forHTTPHeaderField: "X-CSRFToken")
mutableURLRequest.HTTPMethod = "POST"
mutableURLRequest.HTTPBody = postData
let username = "veeru@gmail.com"
let password = "Password123!"

let loginString = NSString(format: "%@:%@", username, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.allZeros)
mutableURLRequest.setValue(base64LoginString, forHTTPHeaderField: "Authorization")
let manager = Alamofire.Manager.sharedInstance // or create a new one
let request = manager.request(mutableURLRequest)
Alamofire.request(.POST, "https://url/account/login",parameters: params)
.responseString{ (request, response, data, error) in
println("Request :\(request)\n\n")
println("Response: \(response)\n\n")
println("Data\(data)")
println("Error : \(error)")
println("Done")
}

Answer

Why do you have the line Alamofire.request(.POST, "https://url/account/login",parameters: params), when you've gone through all the trouble to actually make an NSURLRequest object?

Just remove it:

let request = manager.request(mutableURLRequest)
request.responseString{ (request, response, string, error) in
  // ...
}
Comments