Alamofire Accept and Content-Type JSON

我是研究僧i 提交于 2019-11-29 02:52:21

问题


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

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 is set, but not Accept. How can I do this properly?


回答1:


I ended up using 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
    }
}

And then just:

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

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



回答2:


Example directly from Alamofire github page:

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

In your case add what you want:

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



回答3:


Simple way to use get method with query map and response type 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:


Try this:

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



回答5:


Alamofire.request(url, method: .post, parameters:parameters, encoding: JSONEncoding.default).responseJSON { response in
     ...      
}

it's work



来源:https://stackoverflow.com/questions/28374483/alamofire-accept-and-content-type-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!