Alamofire接受和内容types的JSON

我试图在Swift中用Alamofire做一个GET请求。 我需要设置以下标题:

Content-Type: application/json Accept: application/json 

我可以绕过它,并直接指定请求的标题,但我想要使用ParameterEncoding ,如库中所build议的。 到目前为止,我有这样的:

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

直接来自Alamofire github页面的例子:

 Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]) .validate(statusCode: 200..<300) .validate(contentType: ["application/json"]) .response { (_, _, _, error) in println(error) } 

在你的情况下添加你想要的:

 Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]) .validate(statusCode: 200..<300) .validate(contentType: ["application/json"]) .validate(Accept: ["application/json"]) .response { (_, _, _, error) in println(error) } 

尝试这个:

 URLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") URLRequest.setValue("application/json", forHTTPHeaderField: "Accept")