我刚刚开始了解 Mattt 精彩的新 Alamofire 快速网络库,但不太确定如何将它与自定义标头一起使用。
我尝试从 AFNetworking 转换为 Alamofire 的代码是这样的:
let request = NSMutableURLRequest(URL: url)
request.setValue(authorizationToken, forHTTPHeaderField:"Authorization")
根据官方文档,不建议修改会话配置:
不建议对授权或内容类型标头使用此方法。 相反,使用 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]
对于不同请求之间发生变化的标头,您可以将它们直接传递给请求方法。来自文档:
全局请求方法中直接支持向请求添加自定义 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 对象上执行此操作,正如其他人在此处提到的那样。
此时,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)
}
供参考
我在单独的 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())
对于 Alamofire 5:
let path = BaseServiceApi().baseUrl + "login"
let params = [
"phone": "+9232222222",
"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
}
}
注意:这是 1.0 之前的版本。 它不再有效,请查看已接受的答案。
您可以使用 Manager 单例上的 defaultHeaders 属性来添加标头,如下所示:
Alamofire.Manager.sharedInstance.defaultHeaders.updateValue(authorizationToken, forKey: "Authorization")
至少对我有用。 :)
因为我不喜欢全局设置这些东西(有时我发送它们,有时我不发送),所以我编写了一个包装方法来设置每次调用的标头。
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。
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
}
以下代码设置仅适用于 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 }
您可以将
NSMutableURLRequest
对象直接传递给 Alamofire,因为它具有采用 NSMutableURLRequest
的 URLRequestConvertible
扩展。因此,无需创建自己的类即可添加授权标头。就这么简单:
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) ")
}
}