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?
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)