Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在Swift中发出读取多个参数的post请求?_Ios_Json_Swift_Http_Post - Fatal编程技术网

Ios 如何在Swift中发出读取多个参数的post请求?

Ios 如何在Swift中发出读取多个参数的post请求?,ios,json,swift,http,post,Ios,Json,Swift,Http,Post,我试图向RESTAPI发送一个JSON主体,但它只读取第一个参数,根本无法识别JSON的其余部分。我测试了JSON正文的其他部分的错误输入,并没有像通常那样出现错误 func postRequest(classroomID: String, email: String, vote: String){ //declare parameter as a dictionary which contains string as key and value combination. le

我试图向RESTAPI发送一个JSON主体,但它只读取第一个参数,根本无法识别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()
}
这会将classroomID发布到数据库中,但不会发送电子邮件或投票。 我从这里得到了这个方法:

非常感谢您的帮助


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

我认为您在parameters中提供的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()
}

我认为您在parameters中提供的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()
}

将request.httpBody数据转换为字符串并打印(并告诉我们它是什么)。您是否有API规范或服务器上显示JSON的代码expecting@LouFranco打印request.httpBody数据时得到的唯一结果是132字节。。此外,服务器需要{“ClassroomId”:“api测试”,“最新更新”:“2020-05-07”,“TheVoteData”:[{“电子邮件”:”123@abc.com,“Vote”:“Got it”}]}将request.httpBody数据转换为字符串并打印(并告诉我们它是什么).您是否有API规范或服务器上显示JSON的代码expecting@LouFranco打印request.httpBody数据时得到的唯一结果是132字节。。此外,服务器需要{“ClassroomId”:“api测试”,“最新更新”:“2020-05-07”,“TheVoteData”:[{“电子邮件”:”123@abc.com,“投票”:“明白了”}]}你是对的-我的json不正确!我尝试了这个方法,但仍然得到了相同的结果:classroomid被发布到DB中,但其他的都没有。另一个人问服务器需要什么,这就是--{“ClassroomId”:“api测试”,“最新更新”:“2020-05-07”,“TheVoteData”:[{“Email”:”email@email.email“,”投票“:“明白”}]}--我想知道是否有问题,因为此格式与预期格式略有不同?@JacobBarbush确实如此,您必须确认发送的类型是否与服务器预期的类型相同。例如,如果您的模型(在服务器上)需要一个整数,但您在swift代码中发送了一个字符串,则会出现服务器错误。另外,请确保您的服务器需要一个动态值。如果您的服务器正期待“email@email.email“,它将在尝试发布任何其他值/字符串时失败。你是对的-我的json不正确!我尝试了这个方法,但仍然得到了相同的结果:classroomid被发布到DB中,但其他的都没有。另一个人问服务器需要什么,这就是--{“ClassroomId”:“api测试”,“最新更新”:“2020-05-07”,“TheVoteData”:[{“Email”:”email@email.email“,”投票“:“明白”}]}--我想知道是否有问题,因为此格式与预期格式略有不同?@JacobBarbush确实如此,您必须确认发送的类型是否与服务器预期的类型相同。例如,如果您的模型(在服务器上)需要一个整数,但您在swift代码中发送了一个字符串,则会出现服务器错误。另外,请确保您的服务器需要一个动态值。如果您的服务器正期待“email@email.email,它将在尝试发布任何其他值/字符串时失败。