如何使用Alamofire自定义标头

时间:2014-08-05 16:31:38

标签: swift afnetworking alamofire

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

我尝试将AFNetworking转换为Alamofire的代码是:

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

11 个答案:

答案 0 :(得分:46)

根据官方文档,建议不要修改会话配置:

  

建议不要将其用于授权或内容类型标头。   相反,使用URLRequestConvertible和ParameterEncoding,   分别

因此,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
    }
}

当你想提出请求时:

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

有关URLRequestConvertible的更多信息:https://github.com/Alamofire/Alamofire#urlrequestconvertible

旧答案

截至Alamofire v1.0 Pers答案不再适用。在新版本中,应将其他标头添加到HTTPAdditionalHeaders

NSURLSessionConfiguration属性中
Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization": authorizationToken]

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

答案 1 :(得分:33)

对于从请求更改为请求的标头,您可以将它们直接传递给请求方法。来自the docs

  

直接在全局请求方法中支持向请求添加自定义HTTP标头。这样可以轻松地将HTTP标头附加到可以不断更改的请求。

给出的例子:

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

但是,如果您希望设置不更改的标头,建议您在NSURLConfiguration对象上执行此操作,就像其他人在此处提到的那样。

答案 2 :(得分:26)

目前,Swift 3.0,Xcode 8.x,Alamofire 4.x:

您可以使用自定义标题,如下所示:

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

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

reference

答案 3 :(得分:5)

注意:这是在1.0之前。 不再有效,请查看已接受的答案。


使用Manager单例上的defaultHeaders属性添加标题,如下所示:

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

至少它对我有用。 :)

答案 4 :(得分:5)

因为我不喜欢在全球范围内设置这些东西(有时候我发送它们,有时候我不会),我写了一个包装方法来设置每个调用的标题。

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

可以如下调用......

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*/

它肯定可以通过一些错误检查来清理,但这应该给你一个要点。它全部基于Alamofire 1.2。

答案 5 :(得分:3)

设置以下代码仅适用于iOS 8及更高版本。

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

以下是适用于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 }

更多信息:GitHub - Alamofire Issues

答案 6 :(得分:3)

您可以将NSMutableURLRequest对象直接传递给Alamofire,因为它的NSMutableURLRequest扩展名为URLRequestConvertible。因此,无需创建自己的类来添加Authorization标头。它很简单:

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

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

答案 7 :(得分:3)

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

当Headers在请求中发送时导致问题时,我们需要编码参数,为此我们执行 JSONEncoding.prettyPrinted JSONEncoding.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
 }

答案 8 :(得分:3)

我在一个单独的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
    }
}

我在请求中使用它:

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

答案 9 :(得分:2)

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

答案 10 :(得分:0)

对于Alamofire 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 APIManager
{
    class func headers() -> HTTPHeaders
    {
        let headers: HTTPHeaders = [
            "Content-Type": "application/json",
            "Accept": "application/json"
        ]
        
        return headers
    }
}