在Swift3中发送JSON POST请求

时间:2016-11-18 12:12:41

标签: ios json swift nsurlsession

在我的应用中,我试图用json数据发出http post请求。以下json必须转移到api

{ 
 "Password":"123456",   
 "Email":"test@gmail.com"
}

以下是此任务的代码

let dict = ["Email": "test@gmail.com", "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()
    }

我收到以下错误

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

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

1 个答案:

答案 0 :(得分:18)

尝试两件事:

第一:

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

然后在数据转换为JSON时添加日志。将数据转换为String并打印值。

同时添加

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

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

希望这会对你有所帮助!!

快乐的编码!