【发布时间】:2018-11-20 07:48:21
【问题描述】:
朋友们,我已经浏览了很多示例,这些示例可在 S.O.虽然我没有收到正确的答案,但我仍然面临使用带有 Post 请求的 URLSession 通过 api 请求获取数据并传递参数的问题。
首先,我想告诉你,我有什么。尝试到现在...
func requestApiCall(){
let renewal_id = ""
let policy_no = ""
let client_name = ""
let client_id = ""
let product_name = ""
let created_date_from = ""
let created_date_to = ""
let policy_expiry_from = ""
let policy_expiry_to = ""
self.parameters = ["renewal_id":renewal_id,"policy_no":policy_no,"client_name":client_name,"client_id":client_id,"product_name":product_name,"created_date_from":created_date_from,"created_date_to":created_date_to,"policy_expiry_from":policy_expiry_from,"policy_expiry_to":policy_expiry_to]
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = [
"Accept" : "application/json",
"Content-Type" : "application/x-www-form-urlencoded"
]
let session = URLSession(configuration: config)
let Url = String(format: "http://myapi-url");
let serviceUrl = URL(string: Url)
var request = URLRequest(url: serviceUrl!)
print(request.url!)
request.httpMethod = "POST"
request.timeoutInterval = 60
request.httpBody = try! JSONSerialization.data(withJSONObject: parameters!, options: [])
let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
if error == nil{
print(response!)
}
else {
print(error?.localizedDescription as Any)
}
print(response!)
guard let httpResponse = response as? HTTPURLResponse, let receivedData = data
else {
print("error: not a valid http response")
return
}
switch (httpResponse.statusCode)
{
case 200: //The request was fulfilled
let response = NSString (data: receivedData, encoding: String.Encoding.utf8.rawValue)
if response == "SUCCESS"
{
print("Network - HandShaking Successfull...!!!")
}
else{
print("Network - HandShaking is not successfull...!!!")
}
case 400:
print("response-status - 400 : The request had bad syntax or was inherently impossible to be satisfied.")
case 500:
print("\nresponse-status - 500 : Internal Server Error...!!!")
default:
print("response-status - Unknown : Received Response => \(httpResponse.statusCode)")
}
})
task.resume()
}
运行上述函数后,我得到 httpResponse.statusCode = 500
但是当我在邮递员中运行它时,我得到了正确的响应。
我也尝试过通过邮递员生成code-sn-ps...如下...
func postmanSnippetApiCall(){
let headers = [
"Content-Type": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
"Postman-Token": "5d571157-86c5-4eac-ba6d-b00779ae5dbd"
]
let postData = NSMutableData(data: "renewal_id=".data(using: String.Encoding.utf8)!)
postData.append("&policy_no=".data(using: String.Encoding.utf8)!)
postData.append("&client_name=".data(using: String.Encoding.utf8)!)
postData.append("&client_id=".data(using: String.Encoding.utf8)!)
postData.append("&product_name=".data(using: String.Encoding.utf8)!)
postData.append("&created_date_from=".data(using: String.Encoding.utf8)!)
postData.append("&created_date_to=".data(using: String.Encoding.utf8)!)
postData.append("&policy_expiry_from=".data(using: String.Encoding.utf8)!)
postData.append("&policy_expiry_to=".data(using: String.Encoding.utf8)!)
postData.append("&undefined=undefined".data(using: String.Encoding.utf8)!)
let request = NSMutableURLRequest(url: NSURL(string: "http://myapiurl")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
}
但是在 postman 生成的代码 sn-p 中,我在这一行收到错误,即 request.httpBody = postData as Data 而 error 是这个:Cannot convert value of type 'NSMutableData' to type 'Data' in coercion
如果我使用第三方库,即 Alamofire,那么我可以很容易地获取数据。
Alamofire 代码 sn-p...完美运行..& 给出正确响应。
func apiRequestByAlamofire(){
let urlString = "http://myapiurl"
let params: [String: Any]? = ["renewal_id":"","policy_no":"","client_name":"","client_id":"","product_name":"","created_date_from":"","created_date_to":"","policy_expiry_from":"","policy_expiry_to":""]
Alamofire.request(urlString, method: .post, parameters: params).responseJSON { response in
print(response) //Here getting perfect response successfully...!!!
}
}
但我仍然在通过 URLSession 苦苦挣扎......!!!
我仍然怀疑,为什么我在使用 URLSession 时遇到了太多问题。
以上疑惑的朋友们,请我接受您的建议,并请帮助我理解它。
不知道,我哪里错了。请帮帮我。
【问题讨论】:
-
postman中有生成Code sn-ps的选项,试试看。
-
是的,我也尝试过...但无法解决。获取响应状态为 500。
-
如果您尝试使用 Postman 生成的 Objective-C 代码,它不起作用?
-
嗨 @Larme 你能帮我解决这个问题吗?
-
@Larme 是的,它确实有效
标签: ios swift swift4 nsurlsession swift4.2