Alamofire 接受并 Content-Type JSON

Alamofire Accept and Content-Type JSON

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

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

我可以绕过它并直接为请求指定 headers,但我想按照库中的建议使用 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。我怎样才能正确地做到这一点?

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

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

试试这个:

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

使用具有查询映射和响应类型的 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):    
                }
Alamofire.request(url, method: .post, parameters:parameters, encoding: JSONEncoding.default).responseJSON { response in
     ...      
}

工作正常