Make Requests

Making a request is very simple:

require "httpx"
puts HTTPX.get("https://google.com").to_s #=> "<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">..."

Performing a request will return an HTTPX::Response, which will allow you to perform a few more operations beyond getting the payload. For instance, this is how you’d check it’s status and headers:

require "httpx"
response = HTTPX.get("https://google.com")
puts response.status #=> 302
puts response.headers["location"] #=> "https://www.google.pt/?gfe_rd=cr&dcr=0&ei=v7prWubpNsPBXvDwocAD"

Many other request type methods are available:

require "httpx"
HTTPX.post("http://example.com", body: "blabla")
HTTPX.put("http://example.com")
HTTPX.patch("http://example.com", body: "blabla")
HTTPX.delete("http://example.com")
HTTPX.head("http://example.com")
...

Multiple Requests

Sending multiple requests is as simple as passing them. An array of responses will be returned:

require "httpx"
responses = HTTPX.get("https://www.google.pt/search?q=john", "https://www.google.pt/search?q=paul", "https://www.google.pt/search?q=george", "https://www.google.pt/search?q=ringo")

puts responses.map(&:to_s) #=> "<HTML>..."

# since v0.9, You can also pass different requests like this:

requests = [
  [:get, "https://nnghttp2.org/httpbin/get"],
  [:post, "https://nnghttp2.org/httpbin/post", body: "bla"]
]

responses = HTTPX.request(*requests)

# Or, when a session object is available
session = HTTPX::Session
# or session = HTTPX.plugin(:compression)

requests = [
  session.build_request(:get, "https://nnghttp2.org/httpbin/get"),
  session.build_request(:post,  "https://nnghttp2.org/httpbin/post", body: "bla")
]

responses = HTTPX.request(*requests)

Headers

Headers can either be part of the client’s configuration, or passed to the specific requests.

require "httpx"

http = HTTPX.headers("accept" => "text/html")
http.get("https://google.com") # sends request with "accept: text/html"
http.get("https://google.com", headers: { "accept-language" => "swahili" }) # sends the "accept-language: swahili" along with the previous "accept" header

Next: Pass Parameters