How to Make Http Delete Request in My Ruby Code Using Net::Http

Ruby Net::HTTP delete method with uri params and form data

To pass arguments in url of delete call, you can do the following:

    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)

where body is a hashmap of your parameters:
in your example: {:a=> 'myaccount' :p=>'someprofile'}

Ruby example of Net::HTTP for GET, POST, PUT, DELETE

You would just namespace it:

Net::HTTP::Put.new(uri)

Same with delete:

Net::HTTP::Delete.new(uri)

You can even do that with your existing calls:

conn = Net::HTTP.new(uri)
con.get(path)

that is equivalent to:

Net::HTTP::Get.new(uri)

Executing requests in ruby using net/http

Just at a very quick glance of the documentation, the second argument to get is a hash, and you're passing nil, see:

http.get(uri.request_uri, nil)

Your second attempt should be OK, though I did find that with my setup (ruby 1.9.3 and MacPorts' openssl library) that Net::HTTP was rejecting Facebook's ssl certificate (I was getting "Connection reset by peer". The following code snippet worked for me:

require 'net/http'

API_HOST = "graph.facebook.com"
API_BASE_URL = "https://#{API_HOST}"
path = "/boo"

uri = URI.parse "#{API_BASE_URL}#{path}"
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
res = http.get(uri.request_uri)
puts res.body

Note that I'm not verifying the SSL certificate, which is a potential security problem. As a proof of concept, however, this snippet worked for me - so hopefully this will give you a good data point in your debugging effort.

Payload in Typhoeus Ruby Delete Request

I finally looked at all my requests in which I was payload (POST and PUT) and observed that I was not sending headers along with this DELETE request.

It looks something like this:

query_body = {:bodyHash => body}

request = Typhoeus::Request.new(
url,
body: JSON.dump(query_body),
method: :delete,
ssl_verifypeer: false,
ssl_verifyhost: 0,
verbose: true,
headers: {'X-Requested-With' => 'XMLHttpRequest', 'Content-Type' => 'application/json; charset=utf-8', 'Accept' => 'application/json, text/javascript, */*', 'enctype' => 'application/json'}
)

request.run
response = request.response
http_status = response.code
response.total_time
response.headers
result = JSON.parse(response.body)

Just adding headers to it, made it work



Related Topics



Leave a reply



Submit