Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

swift - How to use Alamofire with custom headers for POST request

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)")
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...