2017-01-01 150 views
0

我正在嘗試使用Alamofire(版本4.0)來提交一些數據的API調用。我認爲這個請求已經成功。但我遇到的麻煩是,當打電話時,我從服務器得到一個0字節失敗的響應。發送Alamofire請求中的JSON數據

我已經嘗試了很多目前在StackOverflow上的解決方案,並且找不到解決方案。謝謝你的幫助。

這裏是我的Postman設置:

enter image description here

我的銀行代碼:

import UIKit 
import Alamofire 

class ViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     let headers: HTTPHeaders = [ "content-type": "x-www-form-urlencoded"] 


     Alamofire.request("myurl.php?method=GET_RECENT", headers: headers).responseJSON { response in 
      debugPrint(response) 
      print(response.request) // original URL request 
      print(response.response) // HTTP URL response 
      print(response.data)  // server data 
      print(response.result) // result of response serialization 

      if let JSON = response.result.value { 
       print("JSON: \(JSON)") 
      } 
     } 

    } 
} 

我得到的錯誤是:

[Request]:myurl.php?method = GET_RECENT [Response]:{URL:myurl.php?method = GET_RECENT} {status code:200,headers {Cache-Control} =「max-age = 0 「; Connection =「Keep-Alive」; 「Content-Length」= 0; 「Content-Type」=「text/html; charset = UTF-8」; Date =「Sun,01 Jan 2017 11:41:31 GMT」; Expires =「Sun,01 Jan 2017 11:41:31 GMT」; 「Keep-Alive」=「timeout = 7,max = 100」; Server =「Apache/2.2.15(CentOS)」; 「X-Powered-By」=「PHP/5.6.25」; }} [數據]:0字節 [結果]:FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength) [時間軸]:時間軸:{ 「請求開始時間」:504963459.698, 「初始響應時間」 :504963459.821,「請求完成時間」:504963459.821,「序列化完成時間」:504963459.821,「等待時間」:0.123秒,「請求持續時間」:0.123秒,「序列化持續時間」:0.001秒, 可選(myurl.php?方法= GET_RECENT) 可選({URL:myurl.php?method = GET_RECENT} {狀態碼:200,標題{「Cache-Control」=「max-age = 0」; Connection =「Keep-Alive」; 「Content-Length」 = 0; 「Content-Type」=「text/html; charset = UTF-8」; Date =「Sun,01 Jan 2017 11:41:31 GMT」; Expires =「Sun,01 Jan 2017 11:41:31 GMT」; 「Keep-Alive」=「timeout = 7,max = 100」; Server =「Apache/2.2.15(CentOS)」; 「X-Powered-By」=「PHP/5.6.25」; }}) 可選(0字節) 故障

+0

你確定你的請求正文有效嗎?這對我來說似乎不是一個有效的'JSON'。 [這](http://www.jsoneditoronline.org/?id=7e091d9ddfc8638b36540ca465d2bba8)會更喜歡它。 – dirtydanee

+0

謝謝。我還不知道JSON請求與html不同。所以你能幫助我嗎? – Travis

+0

你能展示你的代碼生成JSON輸出嗎?你正在嘗試發佈的完整JSON?另外,你從哪裏收到這個錯誤? – dirtydanee

回答

0

我想你設置你郵差的設置是無效的。要發送JSON作爲您的GET請求中的數據,您應該使用raw選項,如下圖所示。

enter image description here

+1

謝謝。我用另一個代碼解決了它!你的回答有幫助! – Travis