gpt4 book ai didi

ios - NSMutableURLRequest - 来自 Swift 数组的 HTTPBody

转载 作者:可可西里 更新时间:2023-11-01 00:16:27 61 4
gpt4 key购买 nike

我需要使用 HTTPBody of Array 向我的服务器发送一个发布请求。这是我的参数数组:

params = [
"message" : [
"alert" : "Find your iPhone",
"sound" : "Binocular_Default.caf"
]
]

现在我需要将 NSMutableURLRequestHTTPBody 设置为这个数组。我该怎么做?

最佳答案

使用您的参数创建可变请求。并尝试使用以下代码

var request = NSMutableURLRequest(URL: NSURL(string: "yoururl"))
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"

//create dictionary with your parameters
var params = ["username":"test", "password":"pass"] as Dictionary<String, String>

var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary

// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
println(err!.localizedDescription)
}
else {

}
})

task.resume()

关于ios - NSMutableURLRequest - 来自 Swift 数组的 HTTPBody,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30816063/

61 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com