我已经尝试了两种方法来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
}
}
TWO - &gt; 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调用并成功到达服务器,但服务器返回错误缺少请求参数。
有趣的是,API在POSTMAN中工作并响应并在我的Objective-C代码中使用AFNetworking。
请告诉我这里做错了什么......
答案 0 :(得分:1)
使用您的第二种方法(URLSession.dataTask)并从参数字典中获取POST字符串,如下所示。希望这将适用于您的情况。
尝试以下代码并告知我们。现在从getDataFromAPI
致电viewDidLoad
并进行测试。
func getPostString(params:[String:Any]) -> String
{
var data = [String]()
for(key, value) in params
{
data.append(key + "=\(value)")
}
return data.map { String($0) }.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()
}