【问题标题】: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 请求?
【发布时间】:2017-12-03 02:10:58
【问题描述】:

下面添加了 Postman api url。

当前代码:

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)
        }}

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

【问题讨论】:

  • 你不要在parameters 参数中传递param
  • stackoverflow.com/questions/42696851/… 来构造 URL?和参数中的 [{fieldName}] 东西
  • 感谢@NiravD 的评论。我有传递参数参数。
  • @Larme Parameters 是这样定义的 public typealias Parameters = [String: Any] 所以你不能用 parameters 参数传递数组
  • 哦,没错,Alamofire 的限制我仍然不明白,而 AFNetworking 接受这两者。

标签: ios json swift3 alamofire


【解决方案1】:

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

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
}

【讨论】:

    【解决方案2】:

    试试这个:使用自定义编码

     struct JSONStringArrayEncoding: ParameterEncoding {
        private let array: [[String : Any]]
    
        init(array: [[String : Any]]) {
            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
        }
    }
    

    通话

    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
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-02
      • 1970-01-01
      • 2017-05-04
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      相关资源
      最近更新 更多