如何在 Alamofire 4.0 中仅使用参数和正文在 swift 中使用 POST 方法发送请求?

Posted

技术标签:

【中文标题】如何在 Alamofire 4.0 中仅使用参数和正文在 swift 中使用 POST 方法发送请求?【英文标题】:How to send request in Alamofire 4.0 only with parameters and Body using POST method in swift? 【发布时间】:2018-03-28 04:18:55 【问题描述】:

我是这样使用的,但是在这种情况下,我需要调用带有参数和 Body 的 API。请帮我。提前致谢。

Alamofire.request(postUrl, method: .post, parameters: params, encoding: CustomPostEncoding(), headers: nil).validate().responseJSON response in

            switch response.result
            
            case .success:
                MBProgressHUD.hide(for: self.view, animated: true)
                if let val = response.result.value
                
                    let json = JSON(val)
                    print(json)
                

            case .failure(let error):
                print(error)
            
        

【问题讨论】:

【参考方案1】:
  var url = "http://..."
    let _headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
    let params : Parameters = ["grant_type":"password","username":"mail","password":"pass"]

    let url =  NSURL(string:"url" as String)

    request(url, method: .post, parameters: params, encoding: URLEncoding.httpBody , headers: _headers).responseJSON(completionHandler: 
        response in response

        let jsonResponse = response.result.value as! NSDictionary

        if jsonResponse["access_token"] != nil
        
            access_token = String(describing: jsonResponse["accesstoken"]!)

        

    )

参考:- POST request with a simple string in body with Alamofire

【讨论】:

实际上我需要将一个字典作为正文传递,并且一次我要发送这样的参数 ["user name" : "Tester", "password" : "123456"] --> 看看这个帖子***.com/questions/31982513/…【参考方案2】:

使用您的参数而不是 class_id 和时间。

func listOfClassesData(url: String,class_id: String,time: String,redClassesData : [String: Any] ,completionHandler:@escaping (Bool) -> ())

            let Auth_header    = ["Authorization" : "Bearer "+getBearerToken()]

            let paameters:Parameters = [
                "class_id" : class_id,
                "time" :time,
            ]

            print(url,Auth_header)
            Alamofire.request(url, method: .post, parameters: paameters, encoding: JSONEncoding.default, headers: Auth_header)
                .responseJSON  response in
                    print(response)
                    switch response.result
                    case .success:
                        let statusCode: Int = (response.response?.statusCode)!
                        switch statusCode
                        case 200:
                            if let json = response.result.value
                                completionHandler(true)
                            
                            break
                        default:
                            completionHandler(false)
                            break
                        
                        break
                    case .failure:
                        completionHandler(false)
                        break
                    
            
        

【讨论】:

【参考方案3】:
let url = "your api url"
let param = ["user":"user@test.com","pass":"12345"]

Alamofire.request(url, method: .post , parameters: param)
.validate()
.responseJSON 
    response in
    switch response.result
    case .success:
        var jsonResult = [String:AnyObject]()
        do
        
            //Get response successfully of api
            jsonResult = try JSONSerialization.jsonObject(with: response.data!, options: []) as! [String:AnyObject]
            print(jsonResult)
        

        catch let error as NSError 
        //get error if there is any problem in response of api.
            print("--->",error)
        
    case .failure(let error):
        //get error if there is any problem while calling api.
        print("---->",error)
    

【讨论】:

以上是关于如何在 Alamofire 4.0 中仅使用参数和正文在 swift 中使用 POST 方法发送请求?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用参数 swift 3.0 Alamofire 4.0 调用邮政服务?

无法在 Alamofire 4.0 中使用类型为“(String,withName:String)”的参数列表调用“附加”

带有 MultiPart 表单数据中的参数的图像上传在 Alamofire 4.0 中不起作用

包装在静态函数中时,Alamofire 4.0“调用中的额外参数'方法'”

如何在 Xcode 8.0 中安装 Alamofire 4.0

如何在部署目标 < 4.0 的项目中仅引用 iOS 4.0 枚举?