如何在 Swift 中使用 JSON 正文发出 HTTP Post 请求

编程入门 行业动态 更新时间:2024-10-24 14:23:05
本文介绍了如何在 Swift 中使用 JSON 正文发出 HTTP Post 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用 JSON 正文发出 HTTP 发布请求:

I'm trying to make an HTTP post request with a JSON body :

如何能够将 NSdictionnary 添加到 HTTP 请求正文中.

How to be able to add an NSdictionnary to the HTTP request body.

这是我的代码,它似乎无法正常工作.

Here is my code, it doesn't seem to work properly.

var entry1 = Response(IdQuestion: 6510,IdProposition: 10,Time: 30) var entry2 = Response(IdQuestion: 8284,IdProposition: 10,Time: 30) Responses.append(entry1) Responses.append(entry2) let list = Responses.map { $0.asDictionary } let json = ["List":list,"IdSurvey":"102","IdUser":"iOSclient","UserInformation":"iOSClient"] let data : NSData = NSKeyedArchiver.archivedDataWithRootObject(json) NSJSONSerialization.isValidJSONObject(json) let myURL = NSURL(string: "www.myserver")! let request = NSMutableURLRequest(URL: myURL) request.HTTPMethod = "POST" request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") request.HTTPBody = data let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in println(response) // Your completion handler code here } task.resume()

推荐答案

试试这个,

// prepare json data let json: [String: Any] = ["title": "ABC", "dict": ["1":"First", "2":"Second"]] let jsonData = try? JSONSerialization.data(withJSONObject: json) // create post request let url = URL(string: "httpbin/post")! var request = URLRequest(url: url) request.httpMethod = "POST" // insert json data to the request request.httpBody = jsonData let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print(error?.localizedDescription ?? "No data") return } let responseJSON = try? JSONSerialization.jsonObject(with: data, options: []) if let responseJSON = responseJSON as? [String: Any] { print(responseJSON) } } task.resume()

或尝试一种方便的方式Alamofire

更多推荐

如何在 Swift 中使用 JSON 正文发出 HTTP Post 请求

本文发布于:2023-06-05 19:38:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/526431.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   正文   Swift   JSON   HTTP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!