Post 方法未在 api 调用中发送我的数据
Post method is not sending my data in api call
嗨,我是 swift 的新手,我进行了以下 api 调用 o 发送数据,但它没有发送,我得到了以下响应。
已发送数据
firstName=gggg&lastName=ggg&username=fgg&password=ghh&email=ggg@gg.com&latitude=25.0710693470323&longitude=55.143004052641
回应
responseString {"status":"error","message":"Oops!!!Something went wrong..."}
但我可以获得所有其他验证消息,例如 "username cannot be empty"。
但我尝试使用 Postman 在 header 方法上它也给出了与上面相同的错误消息,但后来我想出了并发送了 Body 方法和 application/x-www-form-urlencoded 的形式然后我得到了成功响应如下。
以下是我的 API 调用...请有人找出我做错了什么或建议我更好的 post api 调用。
还有一件事是相同的 API 我为“/homefeed”创建的调用方法并得到了响应,但我们不需要为此发送任何特定参数。请帮助我。
func addNewUser()
{
let url = URL(string: "https://xxxxxxxxxx.azurewebsites.net/api/addUser")!
let firstName:String = firstnameTextFeild.text!
let lastName:String = lastNameTxtField.text!
let username:String = usernameTextField.text!
let password:String = passwordTextField.text!
let email:String = emailTextField.text!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "firstName=\(firstName)&lastName=\(lastName)&username=\(username)&password=\(password)&email=\(email)&latitude=\(lat)&longitude=\(long)"
print("Sent Data -",postString)
request.httpBody = postString.data(using: .utf8)
/*
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
*/
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
// print("responseString = \(String(describing: responseString))")
print("responseString ", responseString ?? "resSt")
}
task.resume()
}
您应该像这样传递参数:
let passingDict : [String:Any] = [
"fname" : YourValue,
"lname":YourValue,
"email" : YourValue,
"password" : YourValue,
"countryCode": YourValue,
"mobileNumber": YourValue,
"verificationType":YourValue,
]
let signup_url = ApiList.base_url + ApiList.signup_url
singletonclass.instance.Post_API_Call(passingDict, Url: signup_url, HittingApi: "SIGN_UP_URL")
func Post_API_Call(_ Parame: NSDictionary, Url: String, HittingApi: String)
{
var Api_Resp_Err = String()
var Api_Resp_Dict = NSDictionary()
do
{
let jsonData = try JSONSerialization.data(withJSONObject: Parame, options: [])
let fullListURL = Url
let url = URL(string: Url)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data,response,error in
if error != nil {
DispatchQueue.main.async(execute: {
Api_Resp_Err = (error?.localizedDescription)!
})
return
}
do
{
if let responseJSON = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
{
if responseJSON.count > 0
{
DispatchQueue.main.async(execute: {
let statusCode = responseJSON.object(forKey: "code") as? String ?? ""
let message = responseDict.object(forKey: "Message") as? String ?? ""
})
}
else
{
}
}
else
{
DispatchQueue.main.async(execute: {
Api_Resp_Err = "Data Issue"
})
}
}
catch
{
DispatchQueue.main.async(execute: {
Api_Resp_Err = "Catch Issue"
})
}
}
task.resume()
}
catch
{
DispatchQueue.main.async(execute: {
//print("Server Issue catch II")
})
}
}
使用此代码。它对您有用。
安装 podfile
pod 'Alamofire'
在您的 ViewController
中导入 Alamofire
func addNewUser(){
let url = "your URL"
var param : [String : AnyObject] = [:]
param = ["firstName": firstnameTextFeild.text! as AnyObject,
"lastName": lastNameTxtField.text! as AnyObject,
"username": usernameTextField.text! as AnyObject,
"password": passwordTextField.text! as AnyObject,
"email": emailTextField.text! as AnyObject,
"latitude": "your latitude" as AnyObject,
"longitude": "your longitude" as AnyObject]
print(param)
Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding()).responseJSON { (response:DataResponse<Any>) in
print(response)
if (response.result.value != nil) {
//your code
}
else{
//your code
}
}
}
嗨,我是 swift 的新手,我进行了以下 api 调用 o 发送数据,但它没有发送,我得到了以下响应。
已发送数据
firstName=gggg&lastName=ggg&username=fgg&password=ghh&email=ggg@gg.com&latitude=25.0710693470323&longitude=55.143004052641
回应
responseString {"status":"error","message":"Oops!!!Something went wrong..."}
但我可以获得所有其他验证消息,例如 "username cannot be empty"。
但我尝试使用 Postman 在 header 方法上它也给出了与上面相同的错误消息,但后来我想出了并发送了 Body 方法和 application/x-www-form-urlencoded 的形式然后我得到了成功响应如下。
以下是我的 API 调用...请有人找出我做错了什么或建议我更好的 post api 调用。
还有一件事是相同的 API 我为“/homefeed”创建的调用方法并得到了响应,但我们不需要为此发送任何特定参数。请帮助我。
func addNewUser()
{
let url = URL(string: "https://xxxxxxxxxx.azurewebsites.net/api/addUser")!
let firstName:String = firstnameTextFeild.text!
let lastName:String = lastNameTxtField.text!
let username:String = usernameTextField.text!
let password:String = passwordTextField.text!
let email:String = emailTextField.text!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "firstName=\(firstName)&lastName=\(lastName)&username=\(username)&password=\(password)&email=\(email)&latitude=\(lat)&longitude=\(long)"
print("Sent Data -",postString)
request.httpBody = postString.data(using: .utf8)
/*
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
*/
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
// print("responseString = \(String(describing: responseString))")
print("responseString ", responseString ?? "resSt")
}
task.resume()
}
您应该像这样传递参数:
let passingDict : [String:Any] = [
"fname" : YourValue,
"lname":YourValue,
"email" : YourValue,
"password" : YourValue,
"countryCode": YourValue,
"mobileNumber": YourValue,
"verificationType":YourValue,
]
let signup_url = ApiList.base_url + ApiList.signup_url
singletonclass.instance.Post_API_Call(passingDict, Url: signup_url, HittingApi: "SIGN_UP_URL")
func Post_API_Call(_ Parame: NSDictionary, Url: String, HittingApi: String)
{
var Api_Resp_Err = String()
var Api_Resp_Dict = NSDictionary()
do
{
let jsonData = try JSONSerialization.data(withJSONObject: Parame, options: [])
let fullListURL = Url
let url = URL(string: Url)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data,response,error in
if error != nil {
DispatchQueue.main.async(execute: {
Api_Resp_Err = (error?.localizedDescription)!
})
return
}
do
{
if let responseJSON = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
{
if responseJSON.count > 0
{
DispatchQueue.main.async(execute: {
let statusCode = responseJSON.object(forKey: "code") as? String ?? ""
let message = responseDict.object(forKey: "Message") as? String ?? ""
})
}
else
{
}
}
else
{
DispatchQueue.main.async(execute: {
Api_Resp_Err = "Data Issue"
})
}
}
catch
{
DispatchQueue.main.async(execute: {
Api_Resp_Err = "Catch Issue"
})
}
}
task.resume()
}
catch
{
DispatchQueue.main.async(execute: {
//print("Server Issue catch II")
})
}
}
使用此代码。它对您有用。
安装 podfile
pod 'Alamofire'
在您的 ViewController
中导入 Alamofirefunc addNewUser(){
let url = "your URL"
var param : [String : AnyObject] = [:]
param = ["firstName": firstnameTextFeild.text! as AnyObject,
"lastName": lastNameTxtField.text! as AnyObject,
"username": usernameTextField.text! as AnyObject,
"password": passwordTextField.text! as AnyObject,
"email": emailTextField.text! as AnyObject,
"latitude": "your latitude" as AnyObject,
"longitude": "your longitude" as AnyObject]
print(param)
Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding()).responseJSON { (response:DataResponse<Any>) in
print(response)
if (response.result.value != nil) {
//your code
}
else{
//your code
}
}
}