【问题标题】:Rails RestClient POST request failing with "400 Bad Request"Rails RestClient POST 请求因“400 Bad Request”而失败
【发布时间】:2018-11-15 12:34:23
【问题描述】:

查看文档,没有任何关于如何发出 POST 请求的好例子。我需要使用 auth_token 参数发出 POST 请求并得到回复:

response = RestClient::Request.execute(method: :post,
                        url: 'http://api.example.com/starthere',
                        payload: '{"auth_token" : "my_token"}',
                        headers: {"Content-Type" => "text/plain"}
                       )

400 错误请求错误:

RestClient::BadRequest: 400 Bad Request
    from /Users/me/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rest-client-1.8.0/lib/restclient/abstract_response.rb:74:in `return!'
    from /Users/me/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rest-client-1.8.0/lib/restclient/request.rb:495:in `process_result'
    from /Users/me/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rest-client-1.8.0/lib/me/request.rb:421:in `block in transmit'

有什么好的例子如何使用 RestClient 发出 POST 请求?

编辑:

这是我在模型中提出请求的方式:

  def start
    response = RestClient::Request.execute(method: :post,
                        url: 'http://api.example.com/starthere',
                        payload: '{"auth_token" : "my_token"}',
                        headers: {"Content-Type" => "text/plain"}
                       )
    puts response

  end

【问题讨论】:

  • 你确定你的请求是text/plain请求吗?
  • @Pavan curl 有效,所以我猜它是对的? 'curl "api.example.com/starthere" -d "auth_token=my_token"'
  • 您如何处理控制器的请求?能发下相关代码吗?
  • @Pavan 我只是将它打印到控制台以查看现在的响应
  • 尝试将{"Content-Type" => "text/plain"}更改为{"Content-Type" => "text/html"}

标签: ruby-on-rails rest-client


【解决方案1】:

尝试使用这样的哈希:

def start
   url= 'http://api.example.com/starthere'
   params = {auth_token: 'my_token'}.to_json
   response = RestClient.post url, params
   puts response
end

【讨论】:

    【解决方案2】:

    如果你只是想复制 curl 请求:

    response = RestClient::Request.execute(method: :post, url: 'http://api.example.com/starthere',  payload: {"auth_token" => "my_token"})
    

    以这种格式发布数据时,Curl 和 RestClient 默认使用相同的内容类型(application/x-www-form-urlencoded)。

    【讨论】:

    • 仍然收到“RestClient::BadRequest: 400 Bad Request”
    • @Tom 所以我用你的数据进行了测试,我的 RestClient sn-p 得到了与你 curl 示例完全相同的请求。您确定您将有效负载作为哈希而不是字符串传递吗?
    【解决方案3】:

    如果您在这里遇到同样的问题,请知道这是当您的环境变量未“设置”时发生的常见错误。
    我把它放在引号中是因为你可能已经设置了它但在当前终端会话中不可用! 您可以通过以下方式检查 ENV KEY 是否可用:

    printenv <yourenvkey>

    如果您什么也得不到,则意味着您需要重新添加它或将其放入您的 bash 文件中

    仅供参考:将我的 ENV 变量放入我的 ~/.bash_profile 修复它

    【讨论】:

      猜你喜欢
      • 2019-10-22
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      • 2020-03-19
      • 1970-01-01
      • 2021-09-20
      • 2013-01-12
      • 2017-02-25
      相关资源
      最近更新 更多