ios Alamofire Accept 和 Content-Type JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28374483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:43:19  来源:igfitidea点击:

Alamofire Accept and Content-Type JSON

iosjsonswiftalamofire

提问by jlhonora

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

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

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:

我可以绕过它并直接指定请求的标头,但我想用 来做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-Typeis set, but not Accept. How can I do this properly?

Content-Type已设置,但未设置Accept。我怎样才能正确地做到这一点?

回答by jlhonora

I ended up using URLRequestConvertiblehttps://github.com/Alamofire/Alamofire#urlrequestconvertible

我最终使用了URLRequestConvertiblehttps://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:

另一种方法是为整个会话指定它,检查上面@David 的评论:

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

回答by hasan

Example directly from Alamofire github page:

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

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

回答by Sachin Agrawal

Simple way to use get method with query map and response type json

使用带有查询映射和响应类型 json 的 get 方法的简单方法

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

回答by YI-KUN Chiang

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

it's work

这是工作

回答by Jaydip

Try this:

尝试这个:

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