简体   繁体   English

如何将 Alamofire 与自定义标头一起使用

[英]how to use Alamofire with custom headers

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")

According to the official documentation, modifying the session configuration is not recommended:根据官方文档,不建议修改会话配置:

This is not recommended for Authorization or Content-Type headers.这不推荐用于 Authorization 或 Content-Type 标头。 Instead, use URLRequestConvertible and ParameterEncoding, respectively.相反,分别使用 URLRequestConvertible 和 ParameterEncoding。

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.从 Alamofire v1.0 Pers 开始,答案不再有效。 In the new version additional headers should be added to the HTTPAdditionalHeaders property of NSURLSessionConfiguration在新版本中附加标题被加入到HTTPAdditionalHeaders财产NSURLSessionConfiguration

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

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.全局请求方法直接支持向请求添加自定义 HTTP 标头。 This makes it easy to attach HTTP headers to a Request that can be constantly changing.这使得将 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 对象上这样做,正如其他人在此处提到的那样。

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参考

I've created a static headers method in a separate APIManager class.我在一个单独的 APIManager 类中创建了一个静态头方法。

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())

NOTE : this was before 1.0.注意:这是在 1.0 之前。 It no longer works , look at the accepted answer instead.它不再有效,请改为查看已接受的答案。


You use the defaultHeaders property on the Manager singleton to add headers, like this:您可以使用 Manager 单例上的 defaultHeaders 属性来添加标题,如下所示:

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

At least it works for me.至少它对我有用。 :) :)

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。

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 :当 Headers 在请求中发送时出现问题时,我们需要对参数进行编码,为此我们执行JSONEncoding.prettyPrintedJSONEncoding.default ,例如:

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
 }

Setting below code will only works in iOS 8 and above.以下代码设置仅适用于 iOS 8 及更高版本。

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 问题

You can pass an NSMutableURLRequest object directly to Alamofire, since it has an extension for NSMutableURLRequest that adopts URLRequestConvertible .您可以将NSMutableURLRequest对象直接传递给 Alamofire,因为它具有NSMutableURLRequest的扩展,采用URLRequestConvertible So there's no need to create your own class to just add an Authorization header.所以没有必要创建自己的类来添加一个 Authorization 标头。 It's as simple as this:就这么简单:

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

Alamofire.request(request)
    .responseJSON { (_, _, JSON, error) in }
   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) ")
            }
    }

For Alamofire 5:对于阿拉莫火 5:

let path = BaseServiceApi().baseUrl + "login"

let params = [
    "phone": "+92322222222",
    "password" : "123123123"
    ] as [String : Any]

let request = AF.request(path, method: .post, parameters: params, encoding: JSONEncoding.default, headers: APIManager.headers(), interceptor: nil)

request.responseDecodable(of: UserModel?.self) {(resposnse) in
    
    let user = resposnse.value
    print(user)
}

APIManger Class for headers:标题的 APIManger 类:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM