【问题标题】:Sending JSON POST request in Swift3在 Swift3 中发送 JSON POST 请求
【发布时间】:2017-04-02 06:58:48
【问题描述】:

在我的应用程序中,我正在尝试使用 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.}

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

【问题讨论】:

  • print(response) 和print(json) 的结果是什么?
  • print(response) 的结果是 Optional( { URL: xxxxxxxxx.net/api/Login } { status code: 415, headers { "Content-Length" = 0; Date = "Fri , 2016 年 11 月 18 日 12:20:21 GMT"; 服务器 = "Microsoft-IIS/8.0"; "Set-Cookie" = "ARRAffinity=173cb9da56ba660395def768bf42f0686b2eba6731b99a6d8f2d08471ce133ed;Path=/;Domain=plubmeradmin.azurewebsites.net;" -By" = "ASP.NET"; } }) 但 print(json) 为空
  • 你有你的答案:"Content-Length" = 0。服务器给的数据是空的。另外,看看this Q&A。
  • 谢谢,但我仍然无法理解这是什么原因。可能是我做错了 http 请求?

标签: ios json swift nsurlsession


【解决方案1】:

尝试两件事:

第一:

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

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

同时添加

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

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

希望对你有帮助!!

编码愉快!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    • 2012-12-04
    • 2014-06-25
    相关资源
    最近更新 更多