Ruby Net::HTTP删除方法,带有uri参数和表单数据



这样我就可以用我的RESTapi成功地获得会话令牌,比如:

uri = URI.parse("#{@restapi}/users/login/cloud")
response = Net::HTTP.post_form(uri, {"username" => "jason", "password" => "password123"})

它返回以下JSON:

{ "username" : "jason" , "token" : "1234sometoken567890" , "account" : "myaccount" , "profile" : "main"}

我需要将令牌与表单数据一起使用,以调用API WADL:中所述的此函数

<resource path="/removeProfile">
  <method id="removeProfile" name="DELETE">
    <request>
      <representation mediaType="application/x-www-form-urlencoded">
        <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="a" style="query" type="xs:string"/>
        <param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="p" style="query" type="xs:string"/>
      </representation>
    </request>
    <response>
      <representation mediaType="application/json"/>
    </response>
  </method>
</resource>

这告诉我需要在REST调用中执行以下操作:

1) Request Method:DELETE
2) Form Data a= and p=
3) append the token to the url

在浏览器中,它看起来像:https://my.domain.com/rest/removeProfile?token=1234sometoken567890

带表单数据:

a=myaccount&p=someprofile

我在Ruby中尝试过:

uri = URI.parse("#{@rest}/removeProfile")
# get the token with the connection code
uri.query = URI.encode_www_form(utk: "#{@token}")
http = Net::HTTP.new(uri.host, uri.port)
http.set_form_data({"a" => "#{@account}", "p" => "#{@profile}"})
request = Net::HTTP::Delete.new(uri.path)
response = http.request(request)

尝试模仿卷曲这样做(顺便说一句,这不起作用):

curl -i -X DELETE "https://my.domain.com/rest/removeProfile?utk=1234sometoken567890&a=myaccount&p=someprofile"

发送带有查询字符串参数和表单数据的http DELETE方法的正确方法是什么?

注:

这是我当前的代码:

  def remove_profile(account, profile)
    @account = account
    @profile = profile
    uri = URI.parse("#{@rest}/removeProfile")
    http = Net::HTTP.new(uri.host, uri.port)
    puts 'uri.path = ' + uri.path
    request = Net::HTTP::Delete.new(uri.path)
    request.body = "utk=#{@utk}&a=#{@account}&p=#{@profile}"
    puts 'request.body = ' + request.body
    response = http.request(request)
  end

Ruby爆炸了,堆栈跟踪如下:

/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/net/protocol.rb:153:in `read_nonblock': Connection reset by peer (Errno::ECONNRESET)

知道我在这里做错了什么吗?

要在delete调用的url中传递参数,可以执行以下操作:

    uri = URI.parse('http://localhost/test')
    http = Net::HTTP.new(uri.host, uri.port)
    attribute_url = '?'
    attribute_url << body.map{|k,v| "#{k}=#{v}"}.join('&')
    request = Net::HTTP::Delete.new(uri.request_uri+attribute_url)
    response = http.request(request)

其中body是参数的哈希图:在您的示例中:{:a=> 'myaccount' :p=>'someprofile'}

参数必须在正文中发送,正如application/x-www-form-urlencoded所暗示的那样。在您的cURL示例中,您必须添加-d标志

curl -X DELETE -d "a=myaccount&p=someprofile" "https://my.domain.com/rest/removeProfile"
req = Net::HTTP::Delete.new("/rest/removeProfile")
req.body = "a=myaccount&p=someprofile"

相关内容

  • 没有找到相关文章

最新更新