我正在尝试将curl请求转换为ruby。我不明白为什么会这样:
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 :(得分: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)
答案 1 :(得分:0)
当username
命令将其作为json发送时,您尝试将password
和set_form_data
作为表单编码参数(curl
)发送。尝试将请求的内容主体设置为命令中显示的json。