如何使用Alamofire 4在Swift 3中为JSON数据发送带有参数和正文的POST请求? [英] How to send POST request with both parameter and body for JSON data in Swift 3 using Alamofire 4?
本文介绍了如何使用Alamofire 4在Swift 3中为JSON数据发送带有参数和正文的POST请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
邮差api url在下面添加。
Postman api url added below.
目前代码:
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)
}}
我不知道如何通过此代码添加正文请求。请帮我解决这个问题。
I don't know how to add body request through this code. Please help me to slove this problem.
推荐答案
你在这里混合两件事, page
, size
和 sortBy
您需要将url字符串作为查询字符串传递。现在您的身体请求是 JSON
数组,您只能使用 URLRequest发布带有
。所以试试这样。 Alamofire
的数组
You are mixing two things here, page
,size
and sortBy
is you need to pass with the url string as query string. Now your body is request is JSON
Array and you can post array with Alamofire
only using URLRequest
. So try like this.
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
}
这篇关于如何使用Alamofire 4在Swift 3中为JSON数据发送带有参数和正文的POST请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文