Rails RestClient 发送 POST 请求失败,返回 "400 Bad Request" 错误。

6

查看文档,没有任何关于如何进行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
@Pavan curl 可以工作,所以我想这是正确的吧?'curl "http://api.example.com/starthere" -d "auth_token=my_token"' - Tom
你是如何在控制器中处理请求的?能否发布相关代码? - Pavan
@Pavan 我现在只是将它打印到控制台上,以查看响应。 - Tom
尝试将 {"Content-Type" => "text/plain"} 更改为 {"Content-Type" => "text/html"} - Pavan
显示剩余2条评论
3个回答

1
尝试使用这样的哈希:
def start
   url= 'http://api.example.com/starthere'
   params = {auth_token: 'my_token'}.to_json
   response = RestClient.post url, params
   puts response
end

0

如果你只想复制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
@Tom,我使用了你的数据进行测试,使用我的RestClient片段得到了与你的curl示例完全相同的请求。你确定你传递的负载是哈希而不是字符串吗? - Pafjo

0

如果您看到此页面,遇到相同的问题,请注意这是一个常见错误,当您的环境变量未"设置"时会发生。
我用引号括起来是因为您可能已经设置了它,但在当前终端会话中不可用! 您可以使用以下命令检查ENV KEY是否可用:

printenv <yourenvkey>

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

顺便说一句:将我的ENV变量放在~/.bash_profile中解决了这个问题


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接