2016-11-30 92 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")