Compression reduces transferred data size between client and server. httpx
automatically advertises for, and decompresses data for known compression formats, gzip
and deflate
.
HTTPX.get("https://www.google.com") #=> response with "content-type" as "gzip" or "deflate", response is decoded automatically
Compressing the request payload is a matter of just adding the content-encoding
header with the desired compression format (again, only supports the already mentioned ones):
HTTPX.with(headers: { "content-encoding" => "gzip" }).post("https://filmupload.com", body: File.open("path/to/file"))
httpx
supports “gzip” and “deflate” by default (unsupported encoding formats are ignored).
brotli
compression can be activated by loading the :brotli
plugin (and installing the brotli
gem, which it depends on; caveat: it does not support JRuby).
http = HTTPX.plugin(:brotli)
http.get("https://www.google.com") #=> sends "Accept-Encoding: br, gzip, deflate" header
http = HTTPX.plugin(:brotli)
http.with(headers: { "content-encoding" => "br" }).post("https://filmupload.com", body: File.open("path/to/file"))
By default, httpx
will try to decompress response payloads encoded in a supported compression format (i.e. gzip
). However, there are cases when, as a user, you don’t want to do it, i.e. store the gzipped payload in a file. In such cases, you can set the :decompress_response_body
to false
.
response = HTTPX.get("https://downloads.com/linux-v100.tar.gz", decompress_response_body: false)
response.copy_to("/path/to/linux-distro-tars/linux-v100.tar.gz")
in the same way, you may want to upload a previously-compressed file somewhere. you can then set :compress_request_body
to false
.
response = HTTPX.post(
"https://backups.com/linux",
body: Pathname.new("/path/to/linux-distro-tars/linux-v100.tar.gz"),
headers: { "content-encoding" => "gzip" },
compress_request_body: false
)
Next: Error Handling