8
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.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
unknownbits
  • 2,855
  • 10
  • 41
  • 81

3 Answers3

12
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
Steen
  • 6,573
  • 3
  • 39
  • 56
unknownbits
  • 2,855
  • 10
  • 41
  • 81
4

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
Arie Xiao
  • 13,909
  • 3
  • 31
  • 30
  • getting this error C:\Ruby193>test1.rb C:/Ruby193/test1.rb:4: syntax error, unexpected ':', expecting tASSOC ....query.to_s}", {'Content-Type': 'application/json'}) ... ^ C:/Ruby193/test1.rb:4: syntax error, unexpected '}', expecting $end ...tent-Type': 'application/json'}) ... ^ – unknownbits Apr 15 '13 at 07:03
  • @oecprashant Sorry, that's hash syntax error when typing code. I've updated the answer. – Arie Xiao Apr 15 '13 at 07:11
3

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)
Sean Moubry
  • 1,010
  • 1
  • 13
  • 22
Santhosh
  • 28,097
  • 9
  • 82
  • 87