2015-12-10 76 views
2

我正在嘗試將curl請求轉換爲ruby。我不明白爲什麼這個工程:將Curl請求轉換爲Net :: HTTP時出錯

curl -H "Content-Type: application/json" -X POST -d '{"username":"foo","password":"bar"}' https://xxxxxxxx.ws/authenticate 

雖然這並不:

uri = URI('https://xxxxxxxx.ws/authenticate') 

https = Net::HTTP.new(uri.host,uri.port) 
https.use_ssl = true 

req = Net::HTTP::Post.new(uri) 
req['Content-Type'] = 'application/json' 
req.set_form_data(username: 'foo', password: 'bar') 

res = https.request(req) 

我得到的迴應是:

(byebug) res 
#<Net::HTTPBadRequest 400 Bad Request readbody=true> 
(byebug) res.body 
"{\"error\":\"username needed\"}" 

有沒有什麼辦法來檢查發生了什麼幕後?

+0

你的ruby發送一個純html表單提交,而curl發送json。他們是兩種完全不同的數據格式。 –

回答

1

set_form_data會將請求有效載荷編碼爲www-form-encoded。你需要直接分配主體。

uri = URI('https://xxxxxxxx.ws/authenticate') 

https = Net::HTTP.new(uri.host,uri.port) 
https.use_ssl = true 

req = Net::HTTP::Post.new(uri) 
req['Content-Type'] = 'application/json' 
req.body = { username: 'foo', password: 'bar' }.to_json 

res = https.request(req) 
0

您正在嘗試發送usernamepassword爲形式的編碼參數(set_form_data)當curl命令發送它們作爲JSON。嘗試將請求的內容正文設置爲命令中顯示的json。