Rails RestClient POST请求失败,其中包含" 400 Bad Request"

时间:2016-02-03 11:52:35

标签: ruby-on-rails rest-client

查看文档,没有任何关于如何发出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

3 个答案:

答案 0 :(得分:1)

尝试使用这样的哈希:

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

答案 1 :(得分:0)

如果您只想复制卷曲请求:

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

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

答案 2 :(得分:0)

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

printenv <yourenvkey>

如果您一无所获,则意味着您需要重新添加它或将其放入您的bash文件中

仅供参考:将我的ENV变量固定在我的~/.bash_profile