Question

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.

Was it helpful?

Solution

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

OTHER TIPS

Use instance method Net::HTTP#get to modify the header of a GET request.

require 'net/http'

url = URI.parse('http://www.xyxx/abc/pqr')
http = Net::HTTP.new url.host
resp = http.get("#{url.path}?#{url.query.to_s}", {'Content-Type' => 'application/json'})
data = resp.body
puts data

You can simply do this:

uri = URI.parse('http://www.xyxx/abc/pqr')
req = Net::HTTP::Get.new(uri.path, 'Content-Type' => 'application/json')

res = Net::HTTP.new(uri.host, uri.port).request(req)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top