2016-11-30 93 views
1

我想发布数据起诉POST请求,但每当我发布数据我越来越坏请求错误。JSON POST解析问题在SWIFT 3

请检查验证码,如果有任何问题,请让我知道,

func callDataCall() 
{ 
    let requestURL: NSURL = NSURL(string: "REQUEST_URL")! 

    //convert MID dict to jsondata 
    let NewJSONData = try! JSONSerialization.data(withJSONObject: ["Disease_request":["Mid":self.MedicationID]], options: []) 

    // Convert jsondata to string 
    let NewJSONDataString = NSString(data:NewJSONData, encoding:String.Encoding.utf8.rawValue) as! String 

    print("Created Dictionary is : \(NewJSONDataString)") 

    let urlRequest = NSMutableURLRequest(url: requestURL as URL) 

    // set up the session 
    urlRequest.httpMethod = "POST" 

    urlRequest.httpBody = NewJSONDataString.data(using: String.Encoding.utf8) 

    let task = URLSession.shared.dataTask(with: urlRequest as URLRequest) 
    { 
     data, response, error in 

     let httpResponse = response as! HTTPURLResponse 
     let statusCode = httpResponse.statusCode 

     print("status code is :\(httpResponse)") 

     if (statusCode == 200 || statusCode == 201) 
     { 
      do 
      { 
       let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: AnyObject] 

       if let content = json?["Disease"] as? [[String: AnyObject]] 
       { 
        for i in 0..<content.count 
        { 
         self.medicationContent.append(content[i] as AnyObject) 
        } 
        DispatchQueue.main.async(execute: { 
         self.tableview_Medication.reloadData() 
        }) 
       } 
      } 

      catch 
      { 
       print("Error with Json: \(error)") 
      } 

      self.stopIndicator() 
     } 
    } 
    task.resume() 
} 

的回应是:

<NSHTTPURLResponse: 0x608000231e40> { URL: "REQUEST_URL" } { status code: 400, headers { 
    "Cache-Control" = "no-cache"; 
    "Content-Length" = 46; 
    "Content-Type" = "application/json; charset=utf-8"; 
    Date = "Wed, 30 Nov 2016 10:38:24 GMT"; 
    Expires = "-1"; 
    Pragma = "no-cache"; 
    Server = "Microsoft-IIS/8.5"; 
    "X-AspNet-Version" = "4.0.30319"; 
    "X-Powered-By" = "ASP.NET"; 
    "X-Powered-By-Plesk" = PleskWin; 
} } 

我现在用的是同样的逻辑目标C,它的工作对我来说罚款。

+0

'让reqJSONString = “\(”{\“Disease_request多加一个线\“:”)\(JSONDataString)\(“}”)“'你真的需要将JSONString嵌入到JSON中吗?另外,您可能需要在标题中设置它的长度。 – Larme

+0

真的发表的内容应该是这样的: { “Disease_request”:{ “中”: “37” }} – Piyush

+1

请重构代码中使用斯威夫特原生类型('URL','URLRequest','String' ,[[String:Any]'),标准JSON字典是Swift 3中的[String:Any]',并且忘记了'PrettyPrinted'。服务器根本不在乎。 – vadian

回答

0

得到了解决方案!

雨燕代码是好的,我需要后列举HTTPMethod

所以,现在的代码是这样

urlRequest.httpMethod = "POST"

urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")