如何发出POST请求使用Alamofire 4.0并且参数是文本而不是json

时间:2016-12-21 06:42:29

标签: json swift http post alamofire

我想使用Alamofire 4.0发出POST请求,并且,我希望我的请求参数以文本而不是json的形式传输到服务器。请帮我?谢谢!

2 个答案:

答案 0 :(得分:1)

您应该使用.Custom进行编码参数并创建自己的自定义编码并将其添加到早期alamofire中的HTTP正文中,但在Alamafire 4.0中,您应该扩展ParameterEncoding

extension String: ParameterEncoding {

public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
    var request = try urlRequest.asURLRequest()
    request.httpBody = data(using: .utf8, allowLossyConversion: false)
        return request
    }
}

你可以在这里找到示例代码 - > stack overflow thread

答案 1 :(得分:0)

尝试这样

 func API_getSubject(id:String) {


    MBProgressHUD.showAdded(to: self.view, animated: true)
    let param = ["idnumber" : id];

    print("param == \(param)")

    Alamofire.request(Config.BASE_URL + "subject_list", method: .post, parameters: param, encoding: JSONEncoding.default, headers: nil)
        .responseJSON {
            response in debugPrint(response)     // prints detailed description of all response properties

            //to get JSON return value
            if let result = response.result.value {
                let JSON = result as! NSDictionary

                if JSON.value(forKey: "status") as! NSNumber == 1 {
                    self.ary_responce = (JSON["subjects"]! as! NSArray).mutableCopy() as! NSMutableArray
                    self.aTable.reloadData()
                }
                else{
                    self.Alert(msg: "\(JSON["message"]!)")
                }
            }
            else{
                if let error = response.result.error {
                    self.Alert(msg: error.localizedDescription)
                }
            }
            DispatchQueue.main.async {
                MBProgressHUD.hideAllHUDs(for: self.view, animated: true)
                MBProgressHUD.hide(for: self.view, animated: true)
            }
    }
}