Skip to content
Tony Arcieri edited this page Feb 14, 2016 · 16 revisions

Require the gem in your project:

require 'http'

And make a GET request:

>> HTTP.get('https://www.google.com').to_s
=> "<html><head>..."

The response body is returned. However, we can obtain an HTTP::Response object by removing #to_s to the end of the request:

>> HTTP.get('https://www.google.com')
=> #<HTTP/1.0 200 OK @headers={"Content-Type"=>"text/html; charset=UTF-8", "Date"=>"Fri, ...>

Making POST requests is simple too. Want to POST a form?

HTTP.post('https://example.com/resource', :form => { :foo => "42" })

Making GET requests with query string parameters is as simple.

HTTP.get('https://example.com/resource', :params => { :foo => "bar" })

Want to POST with a specific body, JSON for instance?

HTTP.post('https://example.com/resource', :body => JSON.dump(:foo => '42'))

Or have it serialize JSON for you:

HTTP.post('https://example.com/resource', :json => {:foo => '42'})

Errors

response = HTTP.get('https://example.com')
response.code # 200, 404, etc
response.reason # 'Not Found', 'OK', etc, from server

Clone this wiki locally