如何使用自定义头文件的Alamofire

时间:2021-12-22 06:59:31

I am just starting to take a look at Mattt's wonderful new Alamofire swift networking library and am not quite sure how one would use it with custom headers.

我刚刚开始研究Mattt出色的新Alamofire swift网络库,我不太确定如何将它与自定义头一起使用。

The code i am trying to convert from AFNetworking to Alamofire is this:

我试图从AFNetworking转换到Alamofire的代码是:

let request = NSMutableURLRequest(URL: url)
request.setValue(authorizationToken, forHTTPHeaderField:"Authorization")

10 个解决方案

#1


44  

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.

对于授权或内容类型头,不建议这样做。相反,应该分别使用URLRequestConvertible和parametercoding。

So an example usage of URLRequestConvertible for authorization would be:

因此,URLRequestConvertible用于授权的示例用法是:

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

关于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 v1.0开始,Pers answer将不再工作。在新版本中,应该将附加的header添加到NSURLSessionConfiguration的HTTPAdditionalHeaders属性

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

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

更多信息:https://github.com/Alamofire/Alamofire/issues/111

#2


25  

For headers that change from request to request, you can pass them directly to the request method. From the docs:

对于从请求到请求更改的头,可以直接将它们传递给请求方法。从文档:

Adding a custom HTTP header to a Request is supported directly in the global request method. This makes it easy to attach HTTP headers to a Request that can be constantly changing.

在全局请求方法中直接支持向请求添加自定义HTTP头。这使得将HTTP头附加到不断变化的请求变得很容易。

And the example given:

例子:

    let headers = [
        "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
        "Content-Type": "application/x-www-form-urlencoded"
    ]

    Alamofire.request(.GET, "https://httpbin.org/get", headers: headers)
             .responseJSON { response in
                 debugPrint(response)
             }

If, however, you wish to set headers that do not change, it is recommended that you do so on the NSURLConfiguration object, as others have mentioned here.

但是,如果您希望设置不更改的头,建议您在NSURLConfiguration对象上这样做,就像其他人在这里提到的那样。

#3


23  

At this time , Swift 3.0 , Xcode 8.x, Alamofire 4.x:

此时,Swift 3.0, Xcode 8。x,Alamofire 4. x:

You can use custom header as below:

您可以使用自定义标头如下:

let headers: HTTPHeaders = [
    "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
    "Accept": "application/json"
]

Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in
    debugPrint(response)
}

For reference

供参考

#4


5  

NOTE: this was before 1.0. It no longer works, look at the accepted answer instead.

注意:这是在1.0之前。它不再起作用了,看一看公认的答案。


You use the defaultHeaders property on the Manager singleton to add headers, like this:

您可以在Manager singleton上使用defaultheader属性来添加标题,如下所示:

Alamofire.Manager.sharedInstance.defaultHeaders.updateValue(authorizationToken, forKey: "Authorization")

At least it works for me. :)

至少对我有用。:)

#5


4  

Because I dislike setting these things globally (and sometimes I send them, sometimes I don't), I wrote a wrapper method to set the headers with each call.

因为我不喜欢全局设置这些东西(有时我发送它们,有时我不这样做),所以我编写了一个包装器方法来设置每个调用的头部。

import Alamofire

public class Service: NSObject {

    private class func request(method: Alamofire.Method, URLString: URLStringConvertible, parameters: [String : AnyObject]?, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request {

        let (request, error) = encoding.encode(NSURLRequest(URL: NSURL(string: URLString.URLString)!), parameters: parameters)
        let mutableURLRequest = request as! NSMutableURLRequest

        mutableURLRequest.HTTPMethod = method.rawValue

        if let heads = headers {
            for (field, value) in heads {
                mutableURLRequest.setValue(value, forHTTPHeaderField: field)
            }
        }

        return Alamofire.request(mutableURLRequest)
    }
}

It can be called as follows...

它可以称为……

Service.request(.POST, URLString: "http://httpbin.org/post", parameters: ["example-param": "example-param-value"], encoding: .JSON, headers: ["example-header-field": "example-value"])/*.whatever you want to do with it*/

It could certainly be cleaned up with some error checking, but this should give you the gist of it. It's all based on Alamofire 1.2.

它当然可以用一些错误检查来清理,但是这应该会给你一个要点。这都是基于Alamofire 1.2。

#6


2  

Setting below code will only works in iOS 8 and above.

将下面的代码设置为ios8或以上版本才有效。

Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = headers

Below is the full code which works for iOS 7 and iOS 8

下面是适用于iOS 7和iOS 8的完整代码

let URL = NSURL(string: request.url!)
var mutableURLRequest = NSMutableURLRequest(URL: URL!)
mutableURLRequest.HTTPMethod = Alamofire.Method.GET.rawValue

// Adding headers
var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = defaultHeaders

// Adding parameters
let manager = Alamofire.Manager(configuration: configuration)
let urlReq  = ParameterEncoding.URL.encode(mutableURLRequest, parameters: request.params).0
aReq = manager.request(urlReq)
aReq!.responseJSON { (req, response, JSON, error) in }

More info : GitHub - Alamofire Issues

更多信息:GitHub - Alamofire问题

#7


2  

You can pass an NSMutableURLRequest object directly to Alamofire, since it has an extension for NSMutableURLRequest that adopts URLRequestConvertible. So there's no need to create your own class to just add an Authorization header. It's as simple as this:

您可以将一个NSMutableURLRequest对象直接传递给Alamofire,因为它有一个使用URLRequestConvertible的NSMutableURLRequest扩展。因此不需要创建自己的类来添加授权头。就这么简单:

let request = NSMutableURLRequest(URL: url)
request.setValue(authorizationToken, forHTTPHeaderField:"Authorization")

Alamofire.request(request)
    .responseJSON { (_, _, JSON, error) in }

#8


1  

   let aManager = Manager.sharedInstance
    aManager.session.configuration.HTTPAdditionalHeaders = [
        "Authorization": "Some authentication Token here" ]


    let URL =  "some url string"

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

            if(error != nil)
            {
                if let delegate = self.delegate {
                    delegate.connectionDidFinishedErrorResponceForAction!(1, andWithResponse: nil)
                }
                println("\(error!.localizedDescription)")

            }
            else {

                if let delegate = self.delegate {
                    delegate.connectionDidFinishedForAction!(1, andWithResponse: nil)
                }
               println("req:\(request) \n res:\(response) \n json:\(data!) \n \(error) ")
            }
    }

#9


1  

I've created a static headers method in a separate APIManager class.

我在一个单独的APIManager类中创建了一个静态header方法。

import Foundation
import Alamofire

class APIManager {

    class func headers() -> HTTPHeaders {
        var headers: HTTPHeaders = [
            "Content-Type": "application/json",
            "Accept": "application/json"
        ]

        if let authToken = UserDefaults.standard.string(forKey: "auth_token") {
            headers["Authorization"] = "Token" + " " + authToken
        }

        return headers
    }
}

And I use it in requests:

我用它来申请:

Alamofire.request(urlString,
                      method: .get,
                      headers:APIManager.headers())

#10


0  

Alamofire 4.x, XCode 9.1, Swift 4.x

Alamofire 4。x, XCode 9.1, Swift 4.x。

When Headers cause problem while sending it in the request, then we need to encode parameter, for this we do JSONEncoding.prettyPrinted or JSONEncoding.default like :

当header在发送请求时引起问题时,我们需要对参数进行编码,为此我们进行JSONEncoding。如:

let url = "http:\your.url.string\"
let parameter = ["Username":"name", "Password":"123"]
let headers = ["Content-Type" : "application/json"]

Alamofire.request(url, method : .post, parameters : parameter, encoding : JSONEncoding.default , headers : headers).responseData { dataResponse in

     print(dataResponse.request as Any) // your request 
     print(dataResponse.response as Any) // your response
 }

#1


44  

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.

对于授权或内容类型头,不建议这样做。相反,应该分别使用URLRequestConvertible和parametercoding。

So an example usage of URLRequestConvertible for authorization would be:

因此,URLRequestConvertible用于授权的示例用法是:

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

关于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 v1.0开始,Pers answer将不再工作。在新版本中,应该将附加的header添加到NSURLSessionConfiguration的HTTPAdditionalHeaders属性

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

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

更多信息:https://github.com/Alamofire/Alamofire/issues/111

#2


25  

For headers that change from request to request, you can pass them directly to the request method. From the docs:

对于从请求到请求更改的头,可以直接将它们传递给请求方法。从文档:

Adding a custom HTTP header to a Request is supported directly in the global request method. This makes it easy to attach HTTP headers to a Request that can be constantly changing.

在全局请求方法中直接支持向请求添加自定义HTTP头。这使得将HTTP头附加到不断变化的请求变得很容易。

And the example given:

例子:

    let headers = [
        "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
        "Content-Type": "application/x-www-form-urlencoded"
    ]

    Alamofire.request(.GET, "https://httpbin.org/get", headers: headers)
             .responseJSON { response in
                 debugPrint(response)
             }

If, however, you wish to set headers that do not change, it is recommended that you do so on the NSURLConfiguration object, as others have mentioned here.

但是,如果您希望设置不更改的头,建议您在NSURLConfiguration对象上这样做,就像其他人在这里提到的那样。

#3


23  

At this time , Swift 3.0 , Xcode 8.x, Alamofire 4.x:

此时,Swift 3.0, Xcode 8。x,Alamofire 4. x:

You can use custom header as below:

您可以使用自定义标头如下:

let headers: HTTPHeaders = [
    "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
    "Accept": "application/json"
]

Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in
    debugPrint(response)
}

For reference

供参考

#4


5  

NOTE: this was before 1.0. It no longer works, look at the accepted answer instead.

注意:这是在1.0之前。它不再起作用了,看一看公认的答案。


You use the defaultHeaders property on the Manager singleton to add headers, like this:

您可以在Manager singleton上使用defaultheader属性来添加标题,如下所示:

Alamofire.Manager.sharedInstance.defaultHeaders.updateValue(authorizationToken, forKey: "Authorization")

At least it works for me. :)

至少对我有用。:)

#5


4  

Because I dislike setting these things globally (and sometimes I send them, sometimes I don't), I wrote a wrapper method to set the headers with each call.

因为我不喜欢全局设置这些东西(有时我发送它们,有时我不这样做),所以我编写了一个包装器方法来设置每个调用的头部。

import Alamofire

public class Service: NSObject {

    private class func request(method: Alamofire.Method, URLString: URLStringConvertible, parameters: [String : AnyObject]?, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request {

        let (request, error) = encoding.encode(NSURLRequest(URL: NSURL(string: URLString.URLString)!), parameters: parameters)
        let mutableURLRequest = request as! NSMutableURLRequest

        mutableURLRequest.HTTPMethod = method.rawValue

        if let heads = headers {
            for (field, value) in heads {
                mutableURLRequest.setValue(value, forHTTPHeaderField: field)
            }
        }

        return Alamofire.request(mutableURLRequest)
    }
}

It can be called as follows...

它可以称为……

Service.request(.POST, URLString: "http://httpbin.org/post", parameters: ["example-param": "example-param-value"], encoding: .JSON, headers: ["example-header-field": "example-value"])/*.whatever you want to do with it*/

It could certainly be cleaned up with some error checking, but this should give you the gist of it. It's all based on Alamofire 1.2.

它当然可以用一些错误检查来清理,但是这应该会给你一个要点。这都是基于Alamofire 1.2。

#6


2  

Setting below code will only works in iOS 8 and above.

将下面的代码设置为ios8或以上版本才有效。

Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = headers

Below is the full code which works for iOS 7 and iOS 8

下面是适用于iOS 7和iOS 8的完整代码

let URL = NSURL(string: request.url!)
var mutableURLRequest = NSMutableURLRequest(URL: URL!)
mutableURLRequest.HTTPMethod = Alamofire.Method.GET.rawValue

// Adding headers
var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = defaultHeaders

// Adding parameters
let manager = Alamofire.Manager(configuration: configuration)
let urlReq  = ParameterEncoding.URL.encode(mutableURLRequest, parameters: request.params).0
aReq = manager.request(urlReq)
aReq!.responseJSON { (req, response, JSON, error) in }

More info : GitHub - Alamofire Issues

更多信息:GitHub - Alamofire问题

#7


2  

You can pass an NSMutableURLRequest object directly to Alamofire, since it has an extension for NSMutableURLRequest that adopts URLRequestConvertible. So there's no need to create your own class to just add an Authorization header. It's as simple as this:

您可以将一个NSMutableURLRequest对象直接传递给Alamofire,因为它有一个使用URLRequestConvertible的NSMutableURLRequest扩展。因此不需要创建自己的类来添加授权头。就这么简单:

let request = NSMutableURLRequest(URL: url)
request.setValue(authorizationToken, forHTTPHeaderField:"Authorization")

Alamofire.request(request)
    .responseJSON { (_, _, JSON, error) in }

#8


1  

   let aManager = Manager.sharedInstance
    aManager.session.configuration.HTTPAdditionalHeaders = [
        "Authorization": "Some authentication Token here" ]


    let URL =  "some url string"

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

            if(error != nil)
            {
                if let delegate = self.delegate {
                    delegate.connectionDidFinishedErrorResponceForAction!(1, andWithResponse: nil)
                }
                println("\(error!.localizedDescription)")

            }
            else {

                if let delegate = self.delegate {
                    delegate.connectionDidFinishedForAction!(1, andWithResponse: nil)
                }
               println("req:\(request) \n res:\(response) \n json:\(data!) \n \(error) ")
            }
    }

#9


1  

I've created a static headers method in a separate APIManager class.

我在一个单独的APIManager类中创建了一个静态header方法。

import Foundation
import Alamofire

class APIManager {

    class func headers() -> HTTPHeaders {
        var headers: HTTPHeaders = [
            "Content-Type": "application/json",
            "Accept": "application/json"
        ]

        if let authToken = UserDefaults.standard.string(forKey: "auth_token") {
            headers["Authorization"] = "Token" + " " + authToken
        }

        return headers
    }
}

And I use it in requests:

我用它来申请:

Alamofire.request(urlString,
                      method: .get,
                      headers:APIManager.headers())

#10


0  

Alamofire 4.x, XCode 9.1, Swift 4.x

Alamofire 4。x, XCode 9.1, Swift 4.x。

When Headers cause problem while sending it in the request, then we need to encode parameter, for this we do JSONEncoding.prettyPrinted or JSONEncoding.default like :

当header在发送请求时引起问题时,我们需要对参数进行编码,为此我们进行JSONEncoding。如:

let url = "http:\your.url.string\"
let parameter = ["Username":"name", "Password":"123"]
let headers = ["Content-Type" : "application/json"]

Alamofire.request(url, method : .post, parameters : parameter, encoding : JSONEncoding.default , headers : headers).responseData { dataResponse in

     print(dataResponse.request as Any) // your request 
     print(dataResponse.response as Any) // your response
 }