如何在Swift中使用JSON主体发出HTTP Post请求 [英] How to make HTTP Post request with JSON body in Swift

查看:89
本文介绍了如何在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: "http://www.myserver.com")!
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: "http://httpbin.org/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

or try a convenient way Alamofire

这篇关于如何在Swift中使用JSON主体发出HTTP Post请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆