【发布时间】:2015-12-13 22:33:00
【问题描述】:
我尝试将 JSON 发布到我的 Web 服务器,但它根本不起作用。它适用于 "DELETE" 和 "GET" ,但对于 "POST" 它根本不起作用并获取错误。
这是我的代码:
let postsEndpoint:String = "http://ideabase.herokuapp.com/categories"
guard let postsURL = NSURL(string: postsEndpoint) else {
print("Error: cannot create URL")
return
}
let postsUrlRequest = NSMutableURLRequest(URL: postsURL)
postsUrlRequest.HTTPMethod = "POST"
let newPost: NSDictionary = ["id":7, "title": "Purple","created_at": "2015-12-08 08:06:55","updated_at":"2015-12-08 08:06:55"]
do {
let jsonPost = try NSJSONSerialization.dataWithJSONObject(newPost, options: [])
postsUrlRequest.HTTPBody = jsonPost
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let createTask = session.dataTaskWithRequest(postsUrlRequest, completionHandler: {
(data, response, error) in
guard let responseData = data else {
print("Error: did not receive data")
return
}
guard error == nil else {
print("error calling GET on /categories/1")
print(error)
return
}
// parse the result as JSON, since that's what the API provides
let post: NSDictionary
do {
post = try NSJSONSerialization.JSONObjectWithData(responseData,
options: []) as! NSDictionary
} catch {
print("error parsing response from POST on /categories")
return
}
// now we have the post, let's just print it to prove we can access it
print("The post is: " + post.description)
// the post object is a dictionary
// so we just access the title using the "title" key
// so check for a title and print it if we have one
if let postID = post["id"] as? Int
{
print("The ID is: \(postID)")
}
})
createTask.resume()
我收到错误“从 /categories 上的 POST 解析响应”
你能帮帮我吗?
【问题讨论】:
-
尝试使用 Charles 或其他允许您查看所有进出系统的 http 流量的代理。然后,您可以确保帖子是您所期望的,并查看回复的详细信息。
-
@Gharay,我添加了一个工作 POST 请求的示例
标签: json swift serialization swift2