【问题标题】:forming curl post with json data as swift http post使用 json 数据形成 curl 帖子作为 swift http 帖子
【发布时间】:2017-07-07 09:29:20
【问题描述】:

我有一个 curl 帖子,我想在 swift 中将其转换为 http url 请求:

curl post(命令行):

curl -X POST --header "Content-Type:application/json" --header "Authorization:key=SERVER_KEY" "https://gcm-http.googleapis.com/gcm/send" --data-ascii '{"to":"DEVICE_TOKEN","data":{"uid":"USER_ID"},"priority":10,"notification":{"body":"Hello","badge":"2"}}'

http 请求(快速):

var request = URLRequest(url: URL(string: globalClass.getAppDelegate().global.sendUrl)!)
        request.httpMethod = "POST"

var bodyData:String!

bodyData = "title=\(title)&body=\(message)&user_id=\(user_id)"

request.httpBody = bodyData.data(using: .utf8)

let task = URLSession.shared.dataTask(with: request)

如何将数据部分放入http请求的bodyData中?

"data":{"uid":"USER_ID"}

由于是嵌套结构,不知道怎么形成。

【问题讨论】:

    标签: json swift http url curl


    【解决方案1】:

    斯威夫特 2

    转换成字典:

    let title = "somthing"
    let body = "body text"
    let params = ["title":mail, "body": pass] as Dictionary<String, String>
    

    将字典转换为 JSON:

    do {
            request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: [])
        } catch {
            print("Error")
        }
    

    添加标题

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.addValue(serverKey, forHTTPHeaderField: "Authorization")
    

    编辑:

    将此 JSON 转换为字典:

    "notification":{"body":"Hello","badge":"3"}

    let notification = ["body": "Hello", "badge":"3"]
    let data: [String: AnyObject] = ["notification": notification as AnyObject]
    

    【讨论】:

    • 感谢您的回答。你知道我将如何形成一个像这样的嵌套结构吗? "notification":{"body":"Hello","badge":"3"}
    • @mjpablo23,已添加到帖子中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-07
    • 2011-11-09
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 2013-04-08
    相关资源
    最近更新 更多