【发布时间】:2018-04-24 06:33:10
【问题描述】:
您好,我是 swift 新手,我做了以下 api 调用来发送数据,但它没有发送,我得到了以下响应。
发送数据
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..."}
但我可以获得所有其他验证消息,例如“用户名不能为空”。
但我尝试使用 Postman 它在标题方法上也给出了与上面相同的错误消息,但后来我发现并发送了 Body Method 和 application/x-www-form-urlencoded 的形式,然后我得到了如下的成功响应。
以下是我的 API 调用...请有人找出我做错了什么或建议我更好的发布 api 调用。
还有一件事,这是我为“/homefeed”创建的相同 API 调用方法并获得了响应,但我们不需要为此发送任何特定参数。请帮帮我。
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()
}
【问题讨论】:
-
@Rocky 我正在使用该帖子中的相同 api 调用。我可以获得那些没有参数要发送的 api 的成功响应。但是当我发送参数时,我收到“出现错误消息”
-
取消注释
JSONSerialization语句,将application/x-www-form-urlencoded; charset=utf-8添加到Content-Type,并将parameters变量添加到您的问题中。
标签: ios swift post httprequest swifty-json