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

这是我的 ruby 代码,resp.data以xml形式给我数据。

rest api默认返回xml数据,如果 header content-type为application/json,则返回json。

但我想要json形式的数据。为此,我必须设置header ['content-type'] ='application/json'。

但我不知道,如何使用get_response method.header设置标题以获取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

关于ruby - 如何在Ruby中设置标题['content-type'] ='application/json',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16008978/

10-11 22:34
查看更多