Reputation: 1191
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?
Upvotes: 2
Views: 712
Reputation: 2156
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.
Upvotes: 0
Reputation: 176372
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)
Upvotes: 1