且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用新的Apple Swift语言发布JSON

更新时间:2023-12-03 18:55:16

Nate的答案很棒,但我必须更改request.setvalue才能在我的服务器上运行

Nate's answer was great but I had to change the request.setvalue for it to work on my server

// create the request & response
var request = NSMutableURLRequest(URL: NSURL(string: "http://requestb.in/1ema2pl1"), cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
var response: NSURLResponse?
var error: NSError?

// create some JSON data and configure the request
let jsonString = "json=[{\"str\":\"Hello\",\"num\":1},{\"str\":\"Goodbye\",\"num\":99}]"
request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

// send the request
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)

// look at the response
if let httpResponse = response as? NSHTTPURLResponse {
    println("HTTP response: \(httpResponse.statusCode)")
} else {
    println("No HTTP response")
}