【问题标题】:How to send DELETE request with body using ruby gem?如何使用 ruby​​ gem 发送带有正文的 DELETE 请求?
【发布时间】:2023-03-04 07:34:08
【问题描述】:

我正在与需要使用 JSON 正文的 DELETE 请求的 API 进行通信。这适用于控制台:

curl -XDELETE http://api.com/endpoint_path/rest_resource -d '{"items":[{"type":"type1","item_id":"item1"}]}'

似乎大多数用于发出 HTTP 请求的 gem 不支持带有正文的 DELETE 请求(我尝试过 RestClient 和 Curb)。有没有办法使用一些 Ruby gem(最好是 Curb)或 Net::HTTP 来做到这一点?

【问题讨论】:

    标签: ruby httprequest curb


    【解决方案1】:

    这是使用HTTParty的一种方式:

    HTTParty.delete("http://api.com/endpoint_path/rest_resource", { 
      :body => '{"items":[{"type":"type1","item_id":"item1"}]}'
    })
    

    【讨论】:

      【解决方案2】:

      它可以被她使用。这是 api 的 ORM。 https://github.com/remiprev/her

      使用示例:

      RestResource.destroy_existing(id, body_params)
      

      【讨论】:

        【解决方案3】:

        我也花了一些时间在这个问题上,@Casper 的回答阐明了这一点。

        在我看来,关键是将正文值作为 JSON 字符串传递,这在我找到的大多数文档中都没有写。

        这是另一个使用httpclient的例子

        require 'json'
        body = { 'items': [{ 'type': 'type1', 'item_id': 'item1' }]}
        HTTPClient.new.delete('http://api.com/endpoint_path/rest_resource', body.to_json)
        

        【讨论】:

          猜你喜欢
          • 2010-10-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-07-06
          • 2013-02-16
          • 1970-01-01
          • 2019-10-16
          • 2021-03-12
          相关资源
          最近更新 更多