POST请求不起作用

时间:2016-02-10 13:37:54

标签: ios swift http-post

这是我的prepareForSegue方法

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let vc = segue.destinationViewController as! AllCommentsViewController
    if segue.identifier == "addComment" {
        if let stringText = commentTF.text {
            vc.CommentsArray.append(stringText)

            let urlString = "http://sekaaleksic.cloudlk.com/api/v1/post/comment/\(postId)/submitComment"

            let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
            let session = NSURLSession.sharedSession()
            let params = ["comment=\(stringText)"]

            request.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(params, options: [])
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            request.addValue("application/json", forHTTPHeaderField: "Accept")
            request.addValue("\(stringText)", forHTTPHeaderField: "comment")
            request.HTTPMethod = "POST"

            let task = session.dataTaskWithRequest(request, completionHandler: { data, response, error -> Void in

                print(request.HTTPBody)
                print(params)
                print(error)
                print(response)
                print(data)
            })

            task.resume()

            }

        }
    }
}

那么,问题是什么? 如您所见,我的urlString是用于提交评论的Wordpress API。 postId是帖子的ID。

我应该这样做:$_POST['comment'] = 'some comment message';

但是这段代码不起作用(您可以查看[此链接] [1]上特定帖子的评论数量)

这是XCode日志 - >

["test"]
Optional(<5b22636f 6d6d656e 743d7465 7374225d>)
["comment=test"]
nil
Optional(<NSHTTPURLResponse: 0x137bd1300> { URL: http://sekaaleksic.cloudlk.com/api/v1/post/comment/1/submitComment } { status code: 200, headers {
    "Cache-Control" = "no-cache, must-revalidate, max-age=0, no-cache";
    Connection = "Keep-Alive";
    "Content-Encoding" = gzip;
    "Content-Length" = 70;
    "Content-Type" = "application/json";
    Date = "Wed, 10 Feb 2016 14:00:03 GMT";
    Expires = "Wed, 11 Jan 1984 05:00:00 GMT";
    "Keep-Alive" = "timeout=5, max=700";
    Pragma = "no-cache";
    Server = Apache;
    Vary = "Accept-Encoding";
} })
Optional(<7b227374 61747573 223a6661 6c73652c 22657870 6c61696e 223a2243 6f6d6d65 6e742070 6f737420 69732065 6d707479 227d>)



  [1]: http://sekaaleksic.cloudlk.com/api/v1/post/1/countComments

1 个答案:

答案 0 :(得分:1)

您正在编码JSON错误。

params等于:

["comment": stringText]

JSON用于编码字典,而不是连接字符串。