Ruby on rails Rails RestClient POST请求失败,返回“0”;“400错误请求”;

Ruby on rails Rails RestClient POST请求失败,返回“0”;“400错误请求”;,ruby-on-rails,rest-client,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"}',

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

如果您只想复制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)。

尝试使用如下哈希:

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

如果您在这里遇到同样的问题,只需知道这是一个常见的错误,当您的环境变量未设置时会发生 我把它放在引号中,因为您可能已经设置了它,但在当前终端会话中不可用! 您可以检查环境密钥是否可用于:

printenv

如果你什么也没有得到,那就意味着你需要重新添加它或者把它放在你的
bash
文件中


仅供参考:将我的ENV变量放入我的
~/.bash_配置文件中
修复了它

你确定你的请求是
text/plain
请求吗?@Pavan curl有效,所以我想它是正确的?”curl“-d”auth_token=my_token“您如何在控制器上处理请求?你能发布相关的代码吗?@Pavan我只是将其打印到控制台,以查看现在的响应尝试将
{“Content Type”=>“text/plain”}
更改为
{“Content Type”=>“text/html”}
仍然得到“RestClient::BadRequest:400坏请求”@Tom,所以我使用您的数据进行了测试,得到了与您的示例完全相同的请求。您确定传递的负载是散列而不是字符串吗?