【问题标题】:Error Converting Curl Request to Net::HTTP将 Curl 请求转换为 Net::HTTP 时出错
【发布时间】:2015-12-10 16:12:24
【问题描述】:

我正在尝试将 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\"}"

有没有办法检查幕后发生的事情?

【问题讨论】:

  • 您的 ruby​​ 正在发送纯 html 表单类型的提交,而 curl 正在发送 json。它们是两种完全不同的数据格式。

标签: ruby curl net-http


【解决方案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)

【讨论】:

    【解决方案2】:

    curl 命令以 json 格式发送 usernamepassword 时,您正尝试将它们作为表单编码参数 (set_form_data) 发送。尝试将请求的内容正文设置为命令中显示的 json。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 2017-06-25
      • 2019-08-17
      • 1970-01-01
      • 1970-01-01
      • 2016-08-04
      相关资源
      最近更新 更多