Swift-4 : 如何使用带有 URL 参数的 POST 请求获取数据"Content-Type":"application/x-www-form-urlencoded"



朋友们,我已经看了很多例子,这些例子可以在s.O.上找到。虽然我还没有得到正确的答案,但我仍然面临着使用URLSession和Post request&传递参数。

首先,我想给你看看我有什么。试过了。。。

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

但当我在邮递员中运行这个时,我得到了正确的回应。

邮差Api请求

此外,我还尝试通过邮递员生成代码片段。。。具体如下。。。

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

但在邮递员生成的代码片段中,我在这一行收到错误,即request.httpBody = postData as Data错误是这一个:Cannot convert value of type 'NSMutableData' to type 'Data' in coercion

如果我使用第三方库,即Alamofire,那么我可以非常容易地获取数据。

Alamofire代码片段。。。运行完美&给出适当的响应

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时遇到了太多问题。

朋友们对于以上我的疑问,请我对你的建议持开放态度,也请帮助我理解它。

不知道,我哪里错了。请帮帮我。

经过大量的搜索和斗争,我提出了这个解决方案:

guard var components = URLComponents(url: URL(string: "http://example.com")!, resolvingAgainstBaseURL: true)
else { fatalError("Couldn't create URLComponents") }

components.queryItems = params.map { k, v in URLQueryItem(name: k, value: v) }

var request = URLRequest(url: baseUrl.appendingPathComponent(path.rawValue))
request.httpBody = Data(components.query!.utf8)
request.httpMethod = "POST"

";example.com";因为我只是用URLComponents对参数进行编码。

我给你一个简单的函数,你可以根据你的需求编辑这个函数。您也可以更改您的URL和参数。在响应中,我写了两行代码,如果您从服务器获取JSON数组,那么如果您获取对象,则使用第一行代码,然后使用第二行代码,否则删除这两行代码。

func abc()  {
let request = NSMutableURLRequest(url: URL(string: "Your URL")!)
request.httpMethod = "POST"
let postString = "param_name_one=( value_1 )&param_name_two=(value_2)&........."
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if(error != nil){
// Show Error Message
} else{
do {
//For JSON ARRAY
let jsonItem  = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray
let json = jsonItem[0] as AnyObject
//For JSON object 
let json_object  = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as AnyObject
print(json_object)

} catch {

}
}
}
task.resume();
}

最新更新