Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke HTTP POST method over SSL in ruby?

Tags:

curl

ruby

https

ssl

So here's the request using curl:

curl -XPOST -H content-type:application/json -d "{\"credentials\":{\"username\":\"username\",\"key\":\"key\"}}" https://auth.api.rackspacecloud.com/v1.1/auth 

I've been trying to make this same request using ruby, but I can't seem to get it to work.

I tried a couple of libraries also, but I can't get it to work. Here's what I have so far:

uri = URI.parse("https://auth.api.rackspacecloud.com") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new("/v1.1/auth") request.set_form_data({'credentials' => {'username' => 'username', 'key' => 'key'}}) response = http.request(request) 

I get a 415 unsupported media type error.

like image 595
NielMalhotra Avatar asked Jun 06 '12 17:06

NielMalhotra


1 Answers

You are close, but not quite there. Try something like this instead:

uri = URI.parse("https://auth.api.rackspacecloud.com") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new("/v1.1/auth") request.add_field('Content-Type', 'application/json') request.body = {'credentials' => {'username' => 'username', 'key' => 'key'}}.to_json response = http.request(request) 

This will set the Content-Type header as well as post the JSON in the body, rather than in the form data as your code had it. With the sample credentials, it still fails, but I suspect it should work with real data in there.

like image 130
Eugene Avatar answered Sep 24 '22 03:09

Eugene