How to Use Alamofire with Custom Headers for Post Request

how to use Alamofire with custom headers

According to the official documentation, modifying the session configuration is not recommended:

This is not recommended for Authorization or Content-Type headers.
Instead, use URLRequestConvertible and ParameterEncoding,
respectively.

So an example usage of URLRequestConvertible for authorization would be:

enum Router: URLRequestConvertible {
static let baseUrlString = "some url string"

case Get(query: String)

var URLRequest: NSMutableURLRequest {
let (path: String, parameters: [String: AnyObject]?) = {
switch self {
case .Get(let query):
return ("/get", ["q": query])
}
}()

let URL = NSURL(string: Router.baseUrlString)!
let URLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
// set header fields
URLRequest.setValue("a", forHTTPHeaderField: "Authorization")

let encoding = Alamofire.ParameterEncoding.URL
return encoding.encode(URLRequest, parameters: parameters).0
}
}

and when you want to make a request:

Manager.sharedInstance.request(Router.Get(query: "test"))

More info about URLRequestConvertible: https://github.com/Alamofire/Alamofire#urlrequestconvertible

Old Answer

As of Alamofire v1.0 Pers answer no longer works. In the new version additional headers should be added to the HTTPAdditionalHeaders property of NSURLSessionConfiguration

Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization": authorizationToken]

More info here: https://github.com/Alamofire/Alamofire/issues/111

Alamofire POST request with headers

Add Headers in this way

    let headers = ["Authorization" : "Bearer "+accessToken!+"",
"Content-Type": "application/json"]



Alamofire.request(URL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON
{ (response:DataResponse) in
switch(response.result)
{
case .success(let value):
//for Json serialization add in success:

let JSON = try JSONSerialization.jsonObject(with: response.data! as Data, options:JSONSerialization.ReadingOptions(rawValue: 0))

guard let JSONDictionary: NSDictionary = JSON as? NSDictionary else {

return
}
completionHandler(JSONDictionary as? NSDictionary, nil)
case .failure(let error):
completionHandler(nil, error as NSError?)
break
}

}

Alamofire Request call with: Parameters, Headers and Body not working

Question One

You need to encode as a querystring

let urlString   = "https://intelipos.dynalias.net/ioc/rest.asp"
let parameters = ["action":"heartbeat"]
let headers: HTTPHeaders = ["Content-Type":"application/json"]

AF.request(urlString, method: .post, parameters: parameters, encoding: URLEncoding.queryString, headers: headers).responseJSON { response in
switch response.result {
case .success:
print("Validation Successful")
case let .failure(error):
print(error)
}
}

Question Two

You have to prepare an encodable model and pass it in parameters argument and set encoding to JSONEncoding.default

Refer this article: https://medium.com/whoknows-swift/swift-4-decodable-encodable-3085305a9618

How to use Alamofire with custom headers for POST request

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.

How to send request in Alamofire with parameters and headers using POST method in swift

Alamofire 4.0

let headers = ["Content-Type":"Application/json"]


Alamofire.request(requestString, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
print("Request \(response.request)")

print("RESPONSE \(response.result.value)")
print("RESPONSE \(response.result)")
print("RESPONSE \(response)")


switch response.result {
case .success:


case .failure(let error):


}
}

in 3.0 u can also add headers like this . In parameters to func

Alamofire post request:

There are many ways to implement the requests using Alamofire, this is a simple example:

First, do you have to create the parameters, URL from your API and headers:

let parameters = [
"username": "foo",
"password": "123456"
]

let url = "https://httpbin.org/post"

static private var headers: HTTPHeaders {
get {
return [
"Authorization" : "Bearer \(Session.current.bearerToken ?? "")"
]
}
}

So you call the function from Alamofire and pass your data:

Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON {
response in
switch (response.result) {
case .success:
print(response)
break
case .failure:
print(Error.self)
}
}
}

:)

Alamofire custom header not working

You have to pass Alamofire a NSMutableURLRequest with your customized header. Check out this issue for a better explanation.

        var request = NSMutableURLRequest(URL: NSURL(string: "YOUR URL HERE")!)
request.HTTPMethod = "GET"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
request.addValue("application/vnd.dribbble.v1.text+json", forHTTPHeaderField: "Accept")
//Add paramaters (Optional)
let param = ["foo": "bar"]
let encoding = Alamofire.ParameterEncoding.URL
(request, _) = encoding.encode(request, parameters: param)
Alamofire.request(request).responseJSON { response in
//DO SOMETHING WITH YOUR RESPONSE OBJECT
}

Hope this helps :)



Related Topics



Leave a reply



Submit