Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 256
unknownbits Avatar asked Apr 15 '13 06:04

unknownbits


People also ask

What is headers Content-Type application JSON?

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.

What is application JSON Content-Type?

Content-Type. application/json. Indicates that the request body format is JSON. application/xml. Indicates that the request body format is XML.

Is Content-Type a request header?

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.

Does Axios automatically set Content-Type?

Axios converts this Javascript data to JSON by default. It also sets the “content-type” header to “application/json”.


1 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
like image 153
unknownbits Avatar answered Sep 20 '22 09:09

unknownbits