2

I am trying to translate a curl request to ruby. I don't understand why this works:

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

while this doesn't:

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)

The response I get is:

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

Is there any way to inspect what happens behind the scenes?

aceofbassgreg
  • 3,837
  • 2
  • 32
  • 42
masciugo
  • 1,113
  • 11
  • 19
  • your ruby is sending a plain html form-type submission, while curl is sending json. they're two totally different data formats. – Marc B Dec 10 '15 at 16:18

2 Answers2

1

set_form_data will encode the request payload as www-form-encoded. You need to simply assign the body directly.

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)
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
0

You're trying to send username and password as form-encoded parameters (set_form_data) when the curl command is sending them as json. Try setting the content body of the request to the json shown in the command.

mooiamaduck
  • 2,066
  • 12
  • 13