带标题的Alamofire POST请求

时间:2017-12-12 14:59:04

标签: swift post http-headers alamofire

我正在尝试使用Swift中的Alamofire发送带有标头的帖子请求。但是,我一直在方法调用错误中获得额外参数。我使用的是Alamofire的4.5版本。我无法弄清楚错误。

请找到附带的代码

 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
}

3 个答案:

答案 0 :(得分:6)

以这种方式添加标题

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

//为Json序列化添加成功:

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
                }

        }

答案 1 :(得分: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)
        }
    }

答案 2 :(得分:0)

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