The HTTP protocol allows to carry additional data either by using the request URI, or by using the HTTP body, for which there are a few already widely used standards. HTTPX
aims at solving the majority.
Using the :params
option will encode the parameters in the URI:
# GET https://google.com?q=john
HTTPX.get("http://google.com", params: {"q" => "john"})
Using the :form
option will encode the parameters in the request body encoded in the x-www-form-urlencoded
format:
# POSTed as "foo&bar"
HTTPX.post("https://example.com", form: {"foo" => "bar"})
Important! In order to use this feature, you have to install the multipart plugin.
If you want to upload images, your server will more than probably expect them to be sent using the multipart/form-data
content type:
HTTPX.plugin(:multipart).post("https://example.com", form: {image: File.new(path)})
Using the :json
option will encode the parameters in the application/json
format:
# POSTed as "{'foo': 'bar'}"
HTTPX.post("https://example.com", json: {"foo" => "bar"})
Using the :body
option will pass the raw data to the request body. You can pass:
File
, or a StringIO
object);#each
and yields strings (such as ["a", "b", "c"]
);The content type will be set to application/octet-stream
, unless stated explicitly otherwise.
# body as a string
HTTPX.post("https://example.com", body: "thiswillbethebody")
# body as IO object
HTTPX.post("https://example.com", body: File.open("large-file.txt"))
HTTPX.post("https://example.com", body: StringIO.new("largetext"))
# As an object implementing each
HTTPX.post("https://example.com", body: %w[this will be the body])
# or
fib = Enumerator.new { |y|
a = b = 1
loop {
y << a.to_s
a, b = b, a + b
break if a > 2 ** 32
}
}
HTTPX.post("https://example.com", body: fib)
# Note: The `content-length` header won't be sent in this case, and chunks will be immediately sent to the server when yielded.
If using “HTTP/1.1”, you can set the header, and httpx
will encode it using the chunked transfer encoding immediately:
HTTPX.with(headers: {"transfer-encoding" => "chunked"})
.post("https://example.com", body: %w[this will be the body])
If you want to give the server the opportunity to validate the HTTP request headers before the body is sent, you can just add the expect header, and the client will seamlessly respect it:
HTTPX.post("https://example.com", headers: {"expect" => "100-continue"}, body: File.open("body.txt"))
However, if you aren’t sure if the server you’re requesting from does not handle it, you are strongly recommended to use the expect
plugin instead, which gracefully degrades to sending the body anyway after a timeout if the server doesn’t.
Next: Pass Headers