Alamofire接受和内容类型JSON

时间:2015-02-06 20:44:48

标签: ios json swift alamofire

我正在尝试使用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。我该怎么做呢?

5 个答案:

答案 0 :(得分:13)

我最终使用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")

答案 1 :(得分:5)

直接来自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)
         }

答案 2 :(得分:1)

试试这个:

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

答案 3 :(得分:1)

将get方法与查询映射和响应类型json

一起使用的简单方法
var parameters: [String:Any] = [
            "id": "3"  
        ]
var headers: HTTPHeaders = [
            "Content-Type":"application/json",
            "Accept": "application/json"
        ]
Alamofire.request(url, method: .get,
 parameters: parameters,
encoding: URLEncoding.queryString,headers:headers)
.validate(statusCode: 200..<300)
            .responseData { response in     
                switch response.result {
                case .success(let value):  
                case .failure(let error):    
                }

答案 4 :(得分:1)

foreach ($getAllPermissions as $value) {
    $arrHeader[$value->header_name][$value->sub_header_name][] = $value->name;
}

它的工作