如何 POST 使用 Alamofire/URLSession.dataTask 在 swift 中使用参数请求

How to POST request with parameters using Alamofire/URLSession.dataTask in swift

我已经尝试了两种方法来 POST 请求调用 API。 Alamofire & URLSession.dataTask 但是我无法成功发送参数。

这些是我尝试过的方法

参数

var params :[String: AnyObject]?
    params = ["Some_ID" : "53" as AnyObject, "REQUEST" : "SOME_API_NAME" as AnyObject]

ONE --> Alamofire

Alamofire.request(BaseURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in

        switch(response.result) {
        case .success(_):
            if response.result.value != nil{
                print(response.result.value as Any)
            }
            break

        case .failure(_):
            print(response.result.error as Any)
            break
        }
    }

两个 --> URLSession.dataTask

    if let theJSONData = try? JSONSerialization.data(
        withJSONObject: params as Any,
        options: []) {
        let theJSONText = String(data: theJSONData,
                                 encoding: .ascii)
        print("JSON string = \(theJSONText!)")

        let request = NSMutableURLRequest(url: URL(string:BaseURL)!)
        request.httpMethod = "POST"
        //Here are the required Params.
        let postString = theJSONText

        request.httpBody = postString?.data(using: String.Encoding.utf8)


        let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
            guard error == nil && data != nil else {                                                          // check for fundamental networking error

                print("error=\(String(describing: error))")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
                return
            }
            let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!
            let responseStringForJson = "[\(responseString)]"

            print("result = \(String(describing: responseStringForJson))")

        }
        task.resume()
    }

在这两种情况下,我都面临着同样的问题。 API 调用并成功连接到服务器,但服务器 return 错误 缺少请求参数

有趣的是,API 在 POSTMAN 中工作和响应,并在我的 Objective-C 代码中使用 AFNetworking。

请告诉我我做错了什么...

使用第二种方法 (URLSession.dataTask) 并像这样从参数字典中获取 POST 字符串。希望这对您有用。

试试下面的代码,让我知道。现在从 viewDidLoad 调用 getDataFromAPI 并测试。

func getPostString(params:[String:Any]) -> String
{
    var data = [String]()
    for(key, value) in params
    {
        data.append(key + "=\(value)")
    }
    return data.map { String([=10=]) }.joined(separator: "&")
}

func getDataFromAPI() {

    var params :[String: Any]?
    params = ["Some_ID" : "111", "REQUEST" : "SOME_API_NAME"]

    let url =  URL(string:BaseURL)
    var request = URLRequest(url: url!)
    request.httpMethod = "POST"

    let postString = getPostString(params: params!)
    request.httpBody = postString.data(using: .utf8)

    let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
        guard error == nil && data != nil else {
            print("error=\(String(describing: error))")
            return
        }
        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
            return
        }
        let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!
        let responseStringForJson = "[\(responseString)]"
        print("result = \(String(describing: responseStringForJson))")
    }
    task.resume()
}