【问题标题】:Alamofire POST request with headers带有标头的 Alamofire POST 请求
【发布时间】: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 编译得很好。检查附近某处是否存在语法错误并清理您的项目。
  • 我做到了。所以基本上如果我删除标题;它工作正常。不确定我是否遗漏了什么

标签: swift post http-headers alamofire


【解决方案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
                  }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-23
        • 1970-01-01
        • 1970-01-01
        • 2017-08-31
        • 2018-05-07
        • 2015-03-31
        • 2013-08-03
        • 2020-01-13
        相关资源
        最近更新 更多