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.
Content-Type: application/json is just the content header. The content header is just information about the type of returned data, ex::JSON,image(png,jpg,etc..),html. Keep in mind, that JSON in JavaScript is an array or object.
Content-Type. application/json. Indicates that the request body format is JSON. application/xml. Indicates that the request body format is XML.
The Content-Type http request header specifies the content type of the http request payload. The Content-Type header is NOT tied to the content type of the response sent by the server. Here's an example using pure JavaScript to make an asynchronous HTTP request from the browser.
Axios converts this Javascript data to JSON by default. It also sets the “content-type” header to “application/json”.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With