3

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?

aaa90210
  • 11,295
  • 13
  • 51
  • 88

1 Answers1

4

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
skladd
  • 41
  • 1
  • 3