ios 在 Swift3 中发送 JSON POST 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40676847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 10:49:45  来源:igfitidea点击:

Sending JSON POST request in Swift3

iosjsonswiftnsurlsession

提问by Vah.Sah

In my app i'm trying to make http post request with json data. The following json must be transferred to api

在我的应用程序中,我正在尝试使用 json 数据发出 http post 请求。以下json必须转入api

{ 
 "Password":"123456",   
 "Email":"[email protected]"
}

Here is my code for this task

这是我执行此任务的代码

let dict = ["Email": "[email protected]", "Password":"123456"] as [String: Any]
if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: []) {


    let url = NSURL(string: "http://xxxxxxxxx.net/api/Login")!
    let request = NSMutableURLRequest(url: url as URL)
    request.httpMethod = "POST"

    request.httpBody = jsonData

    let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
        if error != nil{
           print(error?.localizedDescription)
           return
        }

        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

            if let parseJSON = json {
                   let resultValue:String = parseJSON["success"] as! String;
                   print("result: \(resultValue)")
                   print(parseJSON)
                   }
            } catch let error as NSError {
                 print(error)
            }        
       }          
     task.resume()
    }

I'm getting the following error

我收到以下错误

Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}

The response data is empty. What I'm doing wrong, or i have missed something in my code?

响应数据为空。我做错了什么,或者我在我的代码中遗漏了什么?

回答by Sahil Mahajan

Try two things:

尝试两件事:

First :

第一的 :

jsonData = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)

then add logs if your data is converted into JSON. Convert your data into String and print the value.

如果您的数据转换为 JSON,则添加日志。将您的数据转换为字符串并打印值。

Also add

还添加

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

before httpBody. Sometimes we have to tell server in our request that we are posting JSON data.

之前httpBody。有时我们必须在我们的请求中告诉服务器我们正在发布 JSON 数据。

Hope this will help you!!

希望能帮到你!!

Happy Coding!

快乐编码!