【问题标题】:Unable to make HTTP Delete request in my ruby code using Net::HTTP无法使用 Net::HTTP 在我的 ruby​​ 代码中发出 HTTP 删除请求
【发布时间】:2022-05-11 05:00:56
【问题描述】:

我在我的 ruby​​ 代码中使用 Net::HTTP 来发出 http 请求。例如,我做一个发布请求

require 'net/http'
Net::HTTP.post_form(url,{'email' => email,'password' => password})

这行得通。但我无法发出删除请求,即

require 'net/http'
Net::HTTP::Delete(url)

出现以下错误

NoMethodError: undefined method `Delete' for Net::HTTP:Class

http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTP.html 的文档显示删除可用。那么为什么它在我的情况下不起作用?

谢谢

【问题讨论】:

    标签: ruby http rest


    【解决方案1】:

    文档告诉您 Net::HTTP::Delete 是一个类,而不是一个方法。

    改用Net::HTTP.new('www.server.com').delete('/path')

    【讨论】:

      【解决方案2】:
      uri = URI('http://localhost:8080/customer/johndoe')
      http = Net::HTTP.new(uri.host, uri.port)
      req = Net::HTTP::Delete.new(uri.path)
      res = http.request(req)
      puts "deleted #{res}"
      

      【讨论】:

      • 如果需要发送参数:req.body = "name=test&num=1"
      【解决方案3】:

      简单的发布和删除请求,请参阅docs 了解更多信息:

      puts Net::HTTP.new("httpbin.org").post("/post", "a=1").body
      puts Net::HTTP.new("httpbin.org").delete("/delete").body
      

      【讨论】:

        【解决方案4】:

        这对我有用:

        uri = URI(YOUR_URL)
        req = Net::HTTP::Delete.new(uri, {}) # params on second place
        response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
          http.request req
        end
        

        【讨论】:

        • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-05
        • 1970-01-01
        • 2019-11-30
        • 2012-01-09
        • 2023-03-28
        相关资源
        最近更新 更多