如何使用Alamofire 4在Swift 3中为JSON数据发送带有参数和正文的POST请求?

时间:2017-06-29 11:36:21

标签: ios json swift3 alamofire

邮差api url在下面添加。 enter image description here

现在代码:

let baseUrl = "abc.com/search/"
let param  =  [
        "page":"1",
        "size":"5",
        "sortBy":"profile_locality"
    ]

    let headers = [
        "Content-Type": "application/json"
    ]


    Alamofire.SessionManager.default.request("\(baseUrl)field", method: .post,parameters: param, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
        print(response.request ?? "no request")  // original URL request
        if(response.response?.statusCode != nil){
            print("done")
            if self.checkResponse(response.response!.statusCode){
                let json = JSON(data: response.data!)
                //print("at_LeadStop json \(json)")
                return completionHandler(json, false)

            } else {
                return completionHandler(JSON.null, true)
            }
        } else {
            print("gone")
            return completionHandler(JSON.null, true)
        }}

我不知道如何通过此代码添加正文请求。请帮我解决这个问题。

2 个答案:

答案 0 :(得分:16)

您在这里混合了两件事,pagesizesortBy您需要将url字符串作为查询字符串传递。现在您的正文请求为JSON数组,您只能使用Alamofire使用URLRequest发布数组。所以试试这样。

let baseUrl = "abc.com/search/"
let queryStringParam  =  [
    "page":"1",
    "size":"5",
    "sortBy":"profile_locality"
]
//Make first url from this queryStringParam using URLComponents
var urlComponent = URLComponents(string: baseUrl)!
let queryItems = queryStringParam.map  { URLQueryItem(name: $0.key, value: $0.value) }
urlComponent.queryItems = queryItems

//Now make `URLRequest` and set body and headers with it
let param = [
    [
        "fieldName" : "abc",
        "fieldValue":"xyz"
    ],
    [
        "fieldName" : "123",
        "fieldValue":"789"
    ]
]
let headers = [ "Content-Type": "application/json" ]
var request = URLRequest(url: urlComponent.url!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: param)
request.allHTTPHeaderFields = headers

//Now use this URLRequest with Alamofire to make request
Alamofire.request(request).responseJSON { response in
    //Your code
}

答案 1 :(得分:1)

尝试此操作:使用自定义编码

let values  = [
            [
                "fieldName" : "abc",
                "fieldValue":"xyz"
            ],
            [
                "fieldName" : "123",
                "fieldValue":"789"
            ]
        ]

        let param  =  [
            "page":"1",
            "size":"5",
            "sortBy":"profile_locality"
        ]

        let parameterEncoding = JSONStringArrayEncoding.init(array: values)

        Alamofire.request("url", method: .post, parameters: param, encoding:parameterEncoding  ).validate().response { (responseObject) in
            // do your work
        }

<强>调用

div{
display:table;
background-color:#ccc;
height:50px;

}

h4{
display:table-cell;
vertical-align:middle;
}