2017-02-10 146 views
0

我希望有人能夠解釋POST請求(帶參數)是如何實現的。當我運行下面的命令,通過Alamofire的文檔提供,這是生產什麼:Alamofire POST請求

代碼

let url = "https://httpbin.org/post" 
let parameters: Parameters = [ 
     "foo": "bar", 
     "baz": ["a", 1], 
     "qux": [ 
      "x": 1, 
      "y": 2, 
      "z": 3 
     ] 
    ] 


Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in 
    if((response.result.value) != nil) { 
     let jsonVar: JSON = JSON(response.result.value!) 
     print(jsonVar) 
    } 
} 

結果

{ 
"files" : { 

}, 
"origin" : "192.104.181.247", 
"data" : "{\"baz\":[\"a\",1],\"qux\" {\"y\":2,\"x\":1,\"z\":3},\"foo\":\"bar\"}", 
"headers" : { 
"Accept" : "*\/*", 
"Accept-Encoding" : "gzip;q=1.0, compress;q=0.5", 
"Content-Type" : "application\/json", 
"Host" : "httpbin.org", 
"Content-Length" : "53", 
"User-Agent" : "HTTPRequest\/1.0 (com.dexstrum.HTTPRequest; build:1; iOS 10.2.0) Alamofire\/4.3.0", 
"Accept-Language" : "en;q=1.0" 
}, 
"json" : { 
"baz" : [ 
    "a", 
    1 
], 
"foo" : "bar", 
"qux" : { 
    "x" : 1, 
    "y" : 2, 
    "z" : 3 
} 
}, 
"form" : { 

}, 
"args" : { 

}, 
"url" : "https:\/\/httpbin.org\/post" 
} 

究竟與參數和POST請求發生?

回答

1

url你打它允許請求。您可以通過得到json得到方法。通常你通過獲取數據得到方法並通過發送數據方法。當發送數據與請求它需要一些參數滿足其要求,通常是其預定義。

原來你也在這裏與alamofire而且隨着一些參數滿足其要求發送請求。在這裏,你是編碼參數JSONEncoding.default,這意味着它發出的參數編碼爲JSON最後你得到的迴應是JSON因爲你宣佈.responseJSON數據。希望有所幫助。

+0

有幫助。我意識到我的參數可能會傳錯或構造錯誤。 – Dexstrum

+0

我想知道爲什麼我創建的參數沒有正確傳遞。我有讓參數:參數= [「x」:2,「y」:2],這是我的郵編Alamofire.request(url,方法:.post,參數:參數,編碼:JSONEncoding.default).responseJSON在 {響應如果{ 讓jsonVar((response.result.value)=無!)(!response.result.value)JSON = JSON 打印(jsonVar) }其他{ 打印(response.result.value 「無響應」) } } – Dexstrum

+0

它產生一個無響應結果。 – Dexstrum