how to set header['content-type']='application/json' in ruby

unknownbits picture unknownbits · Apr 15, 2013 · Viewed 13.9k times · Source
require 'net/http'

require 'rubygems'

require 'json'

url = URI.parse('http://www.xyxx/abc/pqr')

resp = Net::HTTP.get_response(url) # get_response takes an URI object

data = resp.body

puts data

this is my code in ruby, resp.data is giving me data in xml form.

rest api return xml data by default , and json if header content-type is application/json.

but i want data in json form.for this i have to set header['content-type']='application/json'.

but i do not know , how to set header with get_response method.to get json data.

Answer

unknownbits picture unknownbits · Apr 15, 2013
def post_test
  require 'net/http'
  require 'json'
  @host = '23.23.xxx.xx'
  @port = '8080'
  @path = "/restxxx/abc/xyz"

  request = Net::HTTP::Get.new(@path, initheader = {'Content-Type' =>'application/json'})
  response = Net::HTTP.new(@host, @port).start {|http| http.request(request) }

  puts "Response #{response.code} #{response.message}: #{response.body}"
end