POST请求与Alamofire 4的数据体

编程入门 行业动态 更新时间:2024-10-20 20:34:16
本文介绍了POST请求与Alamofire 4的数据体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何使用Alamofire 4在HTTP主体中发送具有数据的POST请求?我在swift 2.3中使用了自定义编码,这是很好的。我转换了我的代码swift 3,我试图参数编码,但不工作。这个代码:

how is it possible to send a POST request with a data in the HTTP body with Alamofire 4? I used custom encoding at swift 2.3 it was working good. I converted my code swift 3 and I tried to paramater encoding but not working. This code :

public struct MyCustomEncoding : ParameterEncoding { private let data: Data init(data: Data) { self.data = data } public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() do { urlRequest.httpBody = data urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } catch { throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) } return urlRequest }

和Alamofire请求:

and Alamofire request :

let enco : ParameterEncoding = MyCustomEncoding(data: ajsonData) Alamofire.request(urlString, method: .post , parameters: [:], encoding: enco , headers: headers).validate() .responseJSON { response in switch response.result { case .success: print(response) break case .failure(let error): print(error) } }

推荐答案

您需要在swift 3中发送如下所示的请求

You need to send request like below in swift 3

let urlString = "httpbin/get" Alamofire.request(urlString, method: .post, parameters: ["foo": "bar"],encoding: JSONEncoding.default, headers: nil).responseJSON { response in switch response.result { case .success: print(response) break case .failure(let error): print(error) } }

更多推荐

POST请求与Alamofire 4的数据体

本文发布于:2023-11-26 06:55:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633092.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   POST   Alamofire

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!