【问题标题】:How can I make a post request in Swift that reads more than 1 parameter?如何在 Swift 中发出读取超过 1 个参数的发布请求?
【发布时间】:2020-08-22 03:26:15
【问题描述】:

我正在尝试将 JSON 主体发送到 REST API,但它只读取第一个参数,根本无法识别 JSON 的其余部分。我测试了错误输入 JSON 正文的其他部分,但没有像往常一样收到错误。

func postRequest(classroomID: String, email: String, vote: String){

    //declare parameter as a dictionary which contains string as key and value combination.
    let parameters = [
            "classroomID": classroomID,
            "LastUpdated": "2020-01-01",
            "TheVoteData"[
                          "Email": email,
                          "TheVote": vote
              ]
     ]

    //create the url with NSURL
    let url = URL(string: "https://www.api-gateway/dynamoDB/resource")!

    //create the session object
    let session = URLSession.shared

    //now create the Request object using the url object
    var request = URLRequest(url: url)
    request.httpMethod = "POST" //set http method as POST

    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to data object and set it as request body
    } catch let error {
        print(error.localizedDescription)
    }

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

    //create dataTask using the session object to send data to the server
    let task = session.dataTask(with: request, completionHandler: { data, response, error in

        guard error == nil else {
            completion(nil, error)
            return
        }

        guard let data = data else {
            return
        }

        do {
            //create json object from data
            guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] else {
                return
            }
            print(json)
            completion(json, nil)
        } catch let error {
            print(error.localizedDescription)
        }
    })

    task.resume()
}

这会将教室 ID 发布到数据库,但不会发送电子邮件或投票。 我从这里得到了这个方法:How to make HTTP Post request with JSON body in Swift

非常感谢任何帮助!

编辑:我能够通过将 API Gateway 配置为将输入作为简单数组而不是字典数组来解决我的问题。非常感谢所有花时间帮助我的人!

【问题讨论】:

  • 将 request.httpBody 数据转换为字符串并打印出来(告诉我们它是什么)。
  • 您是否有 API 规范或来自服务器的一些代码来显示它所期望的 JSON 格式
  • @LouFranco 当我打印 request.httpBody 数据时我得到的唯一东西是 132 字节。而且,服务器期待 { "ClassroomId":"api-test", "LastUpdated":" 2020-05-07", "TheVoteData":[ { "Email": "123@abc.com", "Vote": "知道了" } ] }

标签: ios json swift http post


【解决方案1】:

我认为您在参数中提供的 JSON 数据无效(我使用 jsonlint.com 检查)试试这个:

func postRequest(classroomID: String, email: String, vote: String){

//declare parameter as a dictionary which contains string as key and value combination.
let parameters: [String:Any] = [
        "classroomID": classroomID,
        "LastUpdated": "2020-01-01",
        "TheVoteData":[
                      "Email": email,
                      "TheVote": vote
    ]
 ]

//create the url with NSURL
let url = URL(string: "https://www.api-gateway/dynamoDB/resource")!


//now create the Request object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST

do {
    request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to data object and set it as request body
} catch let error {
    print(error.localizedDescription)
}

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

let jsonData = try! JSONSerialization.data(withJSONObject: parameters, options: [])
//create dataTask using the session object to send data to the server
 let task = URLSession.shared.uploadTask(with: request, from: jsonData) { data, response, error in
    if let data = data, let dataString = String(data: data, encoding: .utf8) {
        print(dataString)
    }
    //Returns HHTP response if
    if let httpResponse = response as? HTTPURLResponse {
        print(httpResponse.statusCode)
    }
}

task.resume()
}

【讨论】:

  • 你是对的 - 我的 json 不正确!我试过了,我仍然得到相同的结果:classicid to getting posted in the DB,但没有别的。另一个人问服务器在期待什么,这就是 -- { "ClassroomId":"api-test", "LastUpdated":"2020-05-07", "TheVoteData":[ { "Email": "email @email.email", "Vote": "Got it" } ] } -- 我想知道是否存在问题,因为这种格式与预期的有点不同?
  • @JacobBarbush 没错,您必须确认您发送的类型是否与您的服务器期望的相同。例如,如果您的模型(在服务器上)需要一个整数,但您在 swift 代码中发送了一个字符串,您将收到服务器错误。此外,请确保您的服务器期望一个动态值。如果您的服务器完全期望“email@email.email”,则在尝试发布任何其他值/字符串时它将失败。
猜你喜欢
  • 2019-09-17
  • 2016-11-24
  • 1970-01-01
  • 2015-10-09
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-28
相关资源
最近更新 更多