【发布时间】:2018-04-09 12:12:34
【问题描述】:
我有一个 api,我在其中发布一些信息并获得响应并发布它......
代码:
func makePostCall() {
let todosEndpoint: String = "my link"
guard let todosURL = URL(string: todosEndpoint) else {
print("Error: cannot create URL")
return
}
var todosUrlRequest = URLRequest(url: todosURL)
todosUrlRequest.httpMethod = "POST"
let newTodo: [String: Any] = ["name": "Lama", "email": "lama@me.com", "password": "1234"]
let jsonTodo: Data
do {
jsonTodo = try JSONSerialization.data(withJSONObject: newTodo, options: [])
todosUrlRequest.httpBody = jsonTodo
} catch {
print("Error: cannot create JSON from todo")
return
}
let session = URLSession.shared
let task = session.dataTask(with: todosUrlRequest) {
(data, response, error) in
guard error == nil else {
print("error calling POST on /public/api/register_customer")
print(error!)
return
}
guard let responseData = data else {
print("Error: did not receive data")
return
}
// parse the result as JSON, since that's what the API provides
do {
guard let receivedTodo = try JSONSerialization.jsonObject(with: responseData,
options: []) as? [String: Any] else {
print("Could not get JSON from responseData as dictionary")
return
}
print("The todo is: " + receivedTodo.description)
guard let status = receivedTodo["success"] as? Int else {
print("Could not get status from JSON")
return
}
if status == 0{
print("The status is: 0")
guard let message = receivedTodo["message"] as? String else {
print("Could not get message from JSON")
return
}
print("The error is:" + message)
}
else {
print("Success!")
}
} catch {
print("error parsing response from POST on /public/api/register_customer")
return
}
}
task.resume()
}
我得到了这个结果:
The todo is: ["message": {
email = (
"The email field is required."
);
name = (
"The name field is required."
);
password = (
"The password field is required."
);
}, "success": 0]
The status is: 0
Could not get message from JSON
当我没有将这些字段中的任何一个留空并且未检索到消息时..
消息是一个数组,我想显示所有这些
我希望它正确发布...
怎么了?
【问题讨论】:
-
你能在 POSTMAN 上测试吗?我想知道正文是否应该采用
&name=Lama&password=1234&...的形式(有时服务器不能同时处理两者)。 -
@Larme 实际上我做到了,这很有效:/public/api/register_customer?name=lama&email=lama@live.com&password=123
-
在 URL 中有参数的 POST 方法?这不常见。
-
@Larme 不,我不认为它在 URL 中,但我的意思是这些参数在邮递员中与 post 请求一起工作 name=lama&email=lama@live.com&password=123
-
你可以告诉服务器你正在发送 JSON