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

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 ruby ​​code, resp.data gives me data in xml form.

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

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

but I do not know how to set the header using the get_response method. Get json data.

+6
source share
3 answers
 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 
+10
source

Use the instance method Net::HTTP#get to change the header of the 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 
+4
source

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) 
+2
source

All Articles