我正在尝试在 Swift 中使用 Alamofire 发出 GET 请求。我需要设置以下标题:
Content-Type: application/json
Accept: application/json
我可以绕过它并直接指定请求的标头,但我想这样做ParameterEncoding
,正如图书馆中所建议的那样。到目前为止我有这个:
Alamofire.request(.GET, url, encoding: .JSON)
.validate()
.responseJSON { (req, res, json, error) in
if (error != nil) {
NSLog("Error: \(error)")
println(req)
println(res)
} else {
NSLog("Success: \(url)")
var json = JSON(json!)
}
}
Content-Type
已设置,但未设置Accept
。我怎样才能正确地做到这一点?
我最终使用了URLRequestConvertible
https://github.com/Alamofire/Alamofire#urlrequestconvertible
enum Router: URLRequestConvertible {
static let baseUrlString = "someUrl"
case Get(url: String)
var URLRequest: NSMutableURLRequest {
let path: String = {
switch self {
case .Get(let url):
return "/\(url)"
}
}()
let URL = NSURL(string: Router.baseUrlString)!
let URLRequest = NSMutableURLRequest(URL:
URL.URLByAppendingPathComponent(path))
// set header fields
URLRequest.setValue("application/json",
forHTTPHeaderField: "Content-Type")
URLRequest.setValue("application/json",
forHTTPHeaderField: "Accept")
return URLRequest.0
}
}
然后就是:
Alamofire.request(Router.Get(url: ""))
.validate()
.responseJSON { (req, res, json, error) in
if (error != nil) {
NSLog("Error: \(error)")
println(req)
println(res)
} else {
NSLog("Success")
var json = JSON(json!)
NSLog("\(json)")
}
}
另一种方法是为整个会话指定它,请检查上面@David 的评论:
Alamofire.Manager.sharedInstance.session.configuration
.HTTPAdditionalHeaders?.updateValue("application/json",
forKey: "Accept")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)