class HTTP::Client
- HTTP::Client
- Reference
- Object
Overview
An HTTP Client.
NOTE To use Client
, you must explicitly import it with require "http/client"
One-shot usage
Without a block, an HTTP::Client::Response
is returned and the response's body
is available as a String
by invoking HTTP::Client::Response#body
.
require "http/client"
response = HTTP::Client.get "http://www.example.com"
response.status_code # => 200
response.body.lines.first # => "<!doctype html>"
Parameters
Parameters can be added to any request with the URI::Params.encode
method, which
converts a Hash
or NamedTuple
to a URL encoded HTTP query.
require "http/client"
params = URI::Params.encode({"author" => "John Doe", "offset" => "20"}) # => "author=John+Doe&offset=20"
response = HTTP::Client.get URI.new("http", "www.example.com", query: params)
response.status_code # => 200
Streaming
With a block, an HTTP::Client::Response
body is returned and the response's body
is available as an IO
by invoking HTTP::Client::Response#body_io
.
require "http/client"
HTTP::Client.get("http://www.example.com") do |response|
response.status_code # => 200
response.body_io.gets # => "<!doctype html>"
end
Reusing a connection
Similar to the above cases, but creating an instance of an HTTP::Client
.
require "http/client"
client = HTTP::Client.new "www.example.com"
response = client.get "/"
response.status_code # => 200
response.body.lines.first # => "<!doctype html>"
client.close
WARNING A single HTTP::Client
instance is not safe for concurrent use by multiple fibers.
Compression
If compress
isn't set to false
, and no Accept-Encoding
header is explicitly specified,
an HTTP::Client will add an "Accept-Encoding": "gzip, deflate"
header, and automatically decompress
the response body/body_io.
Encoding
If a response has a Content-Type
header with a charset, that charset is set as the encoding
of the returned IO (or used for creating a String for the body). Invalid bytes in the given encoding
are silently ignored when reading text content.