带有标头的 Alamofire POST 请求

Posted

技术标签:

【中文标题】带有标头的 Alamofire POST 请求【英文标题】:Alamofire POST request with headers 【发布时间】:2017-12-12 14:59:03 【问题描述】:

我正在尝试在 Swift 中使用 Alamofire 发出带有标头的发布请求。但是,我不断收到 extra parameter in method call 错误。我正在使用 4.5 版的 Alamofire。我无法弄清楚错误。

请查看附件中的代码

 let headers = ["Authorization": token, "Content-Type": "application/json"]

 Alamofire.request("http://localhost:8000/create", method: .post,  parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON  response in

【问题讨论】:

你的代码 sn-p 编译得很好。检查附近某处是否存在语法错误并清理您的项目。 我做到了。所以基本上如果我删除标题;它工作正常。不确定我是否遗漏了什么 【参考方案1】:

这样添加Header

    let headers = ["Authorization" : "Bearer "+accessToken!+"",
                   "Content-Type": "application/json"]



    Alamofire.request(URL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON
             (response:DataResponse) in
                switch(response.result)
                
                case .success(let value):
//for Json serialization add in success:

    let JSON = try JSONSerialization.jsonObject(with: response.data! as Data, options:JSONSerialization.ReadingOptions(rawValue: 0))

                            guard let JSONDictionary: NSDictionary = JSON as? NSDictionary else 

                                return
                            
                        completionHandler(JSONDictionary as? NSDictionary, nil)
                    case .failure(let error):
                        completionHandler(nil, error as NSError?)
                        break
                    

            

【讨论】:

【参考方案2】:

我使用过如下方式,它对我有用:-

if let url = URL(string: "http://localhost:8000/create") 
    var urlRequest = URLRequest(url: url)
    urlRequest.httpMethod = HTTPMethod.post.rawValue

    urlRequest.addValue(token, forHTTPHeaderField: "Authorization")
    urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")

    Alamofire.request(urlRequest)
        .responseJSON  response in
            self.parseData(response.data!)
    


func parseData(_ data : Data)
        do
            let readableJSON = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String :AnyObject]
            print("readableJSON : \(readableJSON)")
        
        catch
            print(error)
        
    

【讨论】:

【参考方案3】:
func postRequestForAPI(apiType : WSRequestType, parameters : NSDictionary? = nil, completionHandler:@escaping (_ responseObject : NSDictionary?, _ error : NSError?) -> Void)

    if !WSClient.sharedInstance.isConnectedToNetwork()
        CommonUnit.ProgressHud(progressState: ProgressHud_State.StopAnimation)
        CommonUnit.alertController("Network Error", message: "Internet Connection not Available!", okTitle: "Ok", okCompletion: 
        )
        return
    

    let apipath : String = getAPI(apiType: apiType)
    var apiParams : NSDictionary!

    print(parameters ?? "")

    if (parameters != nil)
    
        apiParams = convertDictToJson(dict: parameters!)
    

    print("API : \(apipath)")
    if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String 
        appVersion = version
    

    if CommonUnit.isUserAlreadyLogIn() 
        Constant.Common.headerToken = UserDefaults.standard.value(forKey: Constant.UserDefaultKey.headerToken) as! String
    

    let headers: HTTPHeaders = [
        "header_token": Constant.Common.headerToken,
        "device_type": "1",
        "device_token": Constant.Common.DeviceToken,
        "app_version": appVersion!,
        "app_type":"1",
        "Accept": "application/json"
    ]

    print("headers = \(headers)")
    print(apiParams)
    Alamofire.request(apipath, method: .post, parameters: apiParams as? Parameters, encoding: URLEncoding.default, headers: headers)
        .responseJSON  response in

            switch(response.result) 
            case .success(_):

                do 
                    let JSON = try JSONSerialization.jsonObject(with: response.data! as Data, options:JSONSerialization.ReadingOptions(rawValue: 0))
                    print(JSON)

                    guard let JSONDictionary: NSDictionary = JSON as? NSDictionary else 
                        print("Not a Dictionary")
                        return
                    


                    let badge_count =  String(CommonUnit.checkIfNull(someObject: JSONDictionary[Constant.dictKey.badge_count] as AnyObject))

                    if  badge_count == nil || badge_count == "0"  
                        CommonUnit.btnNotification.badgeString = "0"
                        UIApplication.shared.applicationIconBadgeNumber = 0
                    else
                        CommonUnit.btnNotification.badgeString =  badge_count
                        if (badge_count?.isEmptyString())! == false && CommonUnit.isUserAlreadyLogIn()
                            UIApplication.shared.applicationIconBadgeNumber = Int(badge_count!)!
                        
                    
                    completionHandler(JSONDictionary, nil)
                
                catch let JSONError as NSError 
                    print("\(JSONError)")
                    CommonUnit.ProgressHud(progressState: ProgressHud_State.StopAnimation)
                
                break

            case .failure(_):
                CommonUnit.ProgressHud(progressState: ProgressHud_State.StopAnimation)
                CommonUnit.alertController((response.result.error?.localizedDescription as NSString?)!, message: "", okTitle: "OK", okCompletion: nil)
                print(response.result.error?.localizedDescription as NSString!)
                break
            
    

【讨论】:

以上是关于带有标头的 Alamofire POST 请求的主要内容,如果未能解决你的问题,请参考以下文章

Alamofire - 带有自定义标头的 Rest API 调用

带有标头的 Alamofire 请求?

401 alamofire 获取带有标头的请求

如何在 Alamofire Swift 的 POST 请求中添加标头参数(-H、-u、-X、-d)

如何在 Alamofire 中请求带有正文和标头的 JSON?

Alamofire POST 请求,正文中有一个简单的字符串作为参数,标头仍然显示缺少的参数值