如何使用Alamofire 4在HTTP正文中发送带有数据的POST请求?我在
swift 2.3上使用自定义编码它运行良好.我转换了我的代码swift 3,我尝试使用paramater编码,但没有工作.这段代码:
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要求:
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中发送如下所示的请求
let urlString = "https://httpbin.org/get" Alamofire.request(urlString,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) } }