【问题标题】:Swift : alamofire post with json bodySwift:带有 json 正文的 alamofire 帖子
【发布时间】:2017-06-08 06:38:38
【问题描述】:

我正在使用alarmofire来实现POST请求。

目标是发布为:

curl -X POST --header 'Content-Type: application/json' 
     --header 'Accept: application/json' -d '{"dest":"Place","reason":"Reason","carId":1,"starttime":1496975475840,"departmentId":3,"distance":0.0,"driverId":1}' 
     'http://localhost:8080/serviceCar/v1_0/placeOrder?access_token=25621648-1da5-438e-a52c-f927e2c59de4'

网址是http://localhost:8080/serviceCar/v1_0/placeOrder

我有一个订单类,如何将对象作为请求正文发布,同时将令牌作为表单数据发送?

【问题讨论】:

  • 向我们展示您的 Alamofire 请求代码。

标签: json swift alamofire


【解决方案1】:

Here 是您想要的这种情况。

如果提供的 ParameterEncoding 类型不能满足您的需求,您可以创建自己的自定义编码。这是一个快速示例,说明如何构建自定义 JSONStringArrayEncoding 类型以将 JSON 字符串数组编码到请求中。

struct JSONStringArrayEncoding: ParameterEncoding {
    private let array: [String]

    init(array: [String]) {
        self.array = array
    }

    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var urlRequest = try urlRequest.asURLRequest()

        let data = try JSONSerialization.data(withJSONObject: array, options: [])

        if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
            urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        }

        urlRequest.httpBody = data

        return urlRequest
    }
}

这是设置请求头的示例[from doc]:

let user = "user"
let password = "password"

var headers: HTTPHeaders = [:]

if let authorizationHeader = Request.authorizationHeader(user: user, password: password) {
    headers[authorizationHeader.key] = authorizationHeader.value
}

Alamofire.request("https://httpbin.org/basic-auth/user/password", headers: headers)
    .responseJSON { response in
        debugPrint(response)
    }

【讨论】:

    猜你喜欢
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 2011-10-10
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    相关资源
    最近更新 更多