Alamofire接受和内容类型JSON

编程入门 行业动态 更新时间:2024-10-22 20:28:37
本文介绍了Alamofire接受和内容类型JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用Swift中的Alamofire发出GET请求。我需要设置以下标题:

I'm trying to make a GET request with Alamofire in Swift. I need to set the following headers:

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

我可以破解它并直接指定请求的标题,但我想用它来做 ParameterEncoding ,如库中所示。到目前为止我有这个:

I could hack around it and do it directly specifying the headers for the request, but I want to do it with ParameterEncoding, as is suggested in the library. So far I have this:

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 已设置,但不是接受。我该怎么做呢?

Content-Type is set, but not Accept. How can I do this properly?

推荐答案

我最终使用 URLRequestConvertible github/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上面的评论:

Another way to do it is to specify it for the whole session, check @David's comment above:

Alamofire.Manager.sharedInstance.session.configuration .HTTPAdditionalHeaders?.updateValue("application/json", forKey: "Accept")

更多推荐

Alamofire接受和内容类型JSON

本文发布于:2023-11-26 18:01:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634606.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   内容   Alamofire   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!