29

I implemented a POST request with Alamofire with a custom header, because we work with OAuth2 and we have to send an access token in every request inside the header. In this case I have to use a custom header.

The access token value for the HTTP header field Authorization does not work for me. The server generates an error because the header information for OAuth with the access token is not available.

But what is the mistake in my code?

Here is my current code:

let URL =  NSURL(string: url + "/server/rest/action")
var mutableURLRequest = NSMutableURLRequest(URL: URL!)
mutableURLRequest.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")

//this method does not work anymore because it returns an error in the response
//Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization": "Bearer \(accessToken)"]

Alamofire.Manager.sharedInstance
    .request(.POST, mutableURLRequest, parameters: parameters, encoding: .JSON)
    .validate()
    .responseJSON {
                (request, response, data, error) -> Void in

                NSLog("REQUEST: \(request)")
                NSLog("RESPONSE: \(response)")
                NSLog("DATA: \(data)")
                NSLog("ERROR: \(error)")
    }
Karl
  • 1,601
  • 3
  • 15
  • 13

4 Answers4

45

Here's an example of how I use it with custom headers:

    var manager = Manager.sharedInstance
    // Specifying the Headers we need
    manager.session.configuration.HTTPAdditionalHeaders = [
        "Content-Type": "application/x-www-form-urlencoded",
        "Accept": "application/vnd.lichess.v1+json",
        "X-Requested-With": "XMLHttpRequest",
        "User-Agent": "iMchess"
    ]

Now whenever you make a request, it'll use the specified headers.

Your code refactored: remember to import Alamofire

    let aManager = Manager.sharedInstance
    manager.session.configuration.HTTPAdditionalHeaders = [
        "Authorization": "Bearer \(accessToken)" ]

    let URL =  url + "/server/rest/action"

    request(.POST, URL, encoding: .JSON)
        .responseJSON {
            (request, response, data, error) -> Void in

            println("REQUEST: \(request)")
            println("RESPONSE: \(response)")
            println("DATA: \(data)")
            println("ERROR: \(error)")
    }

This is request signature request(method: Method, URLString: URLStringConvertible>, parameters: [String : AnyObject]?, encoding: ParameterEncoding)

As you can see you don't have to pass an NSURL in it, just the string of the URL, Alamofire takes care of the rest.

leonardo
  • 1,686
  • 15
  • 15
  • For the request it will work, but the answer no longer works. You can see: http://stackoverflow.com/questions/25143938/how-to-use-alamofire-with-custom-headers – Karl Feb 15 '15 at 14:27
  • This is the new way of doing it and it works. Read the Old Answer section from that link, also check: https://github.com/Alamofire/Alamofire/issues/111 - Mattt himself says 'Use the HTTPAdditionalHeaders property ' – leonardo Feb 15 '15 at 14:31
  • I'll refactor your code so that I'll work and post it. – leonardo Feb 15 '15 at 14:41
  • Are you sure the API you're connecting to returns a JSON? – leonardo Feb 15 '15 at 15:17
  • 2
    I think you're right. It is not a JSON which returns. This is a major bug in interface documentation :( Thank you for your help!!! – Karl Feb 15 '15 at 15:21
5

There is a simple solution to send parameters and header with a single Alamofire request for Swift 3 and Alamofire 4.0

    let url = "myURL"
    let parameters: Parameters = [
        "param1": "hello",
        "param2": "world"
    ]
    let headers = [
        "x-access-token": "myToken",
    ]

    Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
        if response.result.isFailure {
            //In case of failure
        }else {
            //in case of success
        }
    }
Kevin ABRIOUX
  • 16,507
  • 12
  • 93
  • 99
1

As of Alamofire 5.0.0, you are able to add a custom HTTP headers using a collection of type HTTPHeader. So to add a custom user agent header you could do as follows: urlRequest.headers.add(.userAgent("Custom User Agent Here"))

Dom Bryan
  • 1,238
  • 2
  • 19
  • 39
0
let headers: HTTPHeaders = [
        "Cookie": UserDefaultsUtil.getString(param: Constants.COOKIE),
        "Accept": "application/json"
    ]

Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
        .responseObject { (response: DataResponse<Any>) in
            if response.result.isSuccess {

            }
            else {

            }
    }