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

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

内容简介:翻译自: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请求》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Computational Geometry

Computational Geometry

Mark de Berg、Otfried Cheong、Marc van Kreveld、Mark Overmars / Springer / 2008-4-16 / USD 49.95

This well-accepted introduction to computational geometry is a textbook for high-level undergraduate and low-level graduate courses. The focus is on algorithms and hence the book is well suited for st......一起来看看 《Computational Geometry》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具