ios – 带有Alamofire 4的数据的POST请求

栏目: Swift · 发布时间: 5年前

内容简介:翻译自:https://stackoverflow.com/questions/40604502/post-request-with-data-in-body-with-alamofire-4
如何使用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, 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)
                }
}

翻译自:https://stackoverflow.com/questions/40604502/post-request-with-data-in-body-with-alamofire-4


以上所述就是小编给大家介绍的《ios – 带有Alamofire 4的数据的POST请求》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Clean Architecture

Clean Architecture

Robert C. Martin / Prentice Hall / 2017-9-20 / USD 34.99

Practical Software Architecture Solutions from the Legendary Robert C. Martin (“Uncle Bob”) By applying universal rules of software architecture, you can dramatically improve developer producti......一起来看看 《Clean Architecture》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

html转js在线工具
html转js在线工具

html转js在线工具