jlh*_*ora 11 json ios swift alamofire
我正试图在Swift中向Alamofire提出GET请求.我需要设置以下标题:
Content-Type: application/json
Accept: application/json
Run Code Online (Sandbox Code Playgroud)
我可以破解它并直接指定请求的标题,但我想这样做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!)
}
}
Run Code Online (Sandbox Code Playgroud)
Content-Type设定,但不是Accept.我该怎么做呢?
jlh*_*ora 14
我最终使用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
}
}
Run Code Online (Sandbox Code Playgroud)
然后就是:
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)")
}
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是为整个会话指定它,检查上面@ David的评论:
Alamofire.Manager.sharedInstance.session.configuration
.HTTPAdditionalHeaders?.updateValue("application/json",
forKey: "Accept")
Run Code Online (Sandbox Code Playgroud)
直接来自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)
}
Run Code Online (Sandbox Code Playgroud)
在你的情况下添加你想要的:
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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22610 次 |
| 最近记录: |