Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Net::HTTP POST send data gzip compressed

I am using Net::HTTP::Post under JRUBY 1.9.2 to send data to a custom server (not a web server), that want the data to be gzipped compressed.

How can I tell Net::HTTP::Post to gzip compress the data it is POSTING?

like image 240
aaa90210 Avatar asked Nov 26 '25 17:11

aaa90210


1 Answers

Example for posting JSON:

require('zlib')
require('net/http')
require('json')

data = {my: 'data'}
uri = URI('http://example.com/api/endpoint')

headers = {
  'Content-Type' => 'application/json',
  'Content-Encoding' => 'gzip',
}
request = Net::HTTP::Post.new(uri, headers)

gzip = Zlib::GzipWriter.new(StringIO.new)
gzip << data.to_json
request.body = gzip.close.string

response = Net::HTTP.start(uri.hostname, uri.port) do |http|
  http.request(request)
end
like image 55
skladd Avatar answered Nov 28 '25 11:11

skladd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!