62

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

我试图从 AFNetworking 转换为 Alamofire 的代码是这样的:

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

11 回答 11

51

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

对于 Authorization 或 Content-Type 标头,不建议这样做。相反,请分别使用 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 答案不再有效。在新版本中,应将附加标头添加HTTPAdditionalHeadersNSURLSessionConfiguration

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

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

于 2014-09-26T08:53:18.920 回答
40

对于从请求到请求而变化的标头,您可以将它们直接传递给请求方法。从文档

全局请求方法直接支持向请求添加自定义 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 对象上执行此操作,正如其他人在此处提到的那样。

于 2016-03-30T04:56:43.210 回答
36

此时,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)
}

参考

于 2016-10-12T14:13:52.733 回答
12

我在单独的 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())
于 2017-12-17T14:15:23.083 回答
6

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


您可以使用 Manager 单例上的 defaultHeaders 属性来添加标头,如下所示:

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

至少它对我有用。:)

于 2014-08-13T15:37:17.977 回答
5

Alamofire 4.x、XCode 9.1、Swift 4.x

当 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
 }
于 2017-12-06T10:42:10.223 回答
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。

于 2015-07-13T21:30:15.360 回答
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 问题

于 2015-02-09T08:11:27.300 回答
3

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

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

Alamofire.request(request)
    .responseJSON { (_, _, JSON, error) in }
于 2015-07-09T13:17:41.007 回答
3
   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) ")
            }
    }
于 2015-07-23T05:42:43.230 回答
1

对于 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
    }
}
于 2020-08-18T12:23:51.873 回答