Ruby 如何设置标题[';内容类型';]=';application/json';红宝石色

Ruby 如何设置标题[';内容类型';]=';application/json';红宝石色,ruby,rest,net-http,Ruby,Rest,Net Http,这是我在ruby中的代码,resp.data以xml形式提供数据 RESTAPI默认返回xml数据,如果标头内容类型为application/json,则返回json 但我需要json格式的数据。为此,我必须设置头['content-type']='application/json' 但是我不知道,如何使用get_response method设置标头来获取json数据。使用实例方法修改get请求的标头 需要“net/http” url=URI.parse('http://www.xyxx/ab

这是我在ruby中的代码,resp.data以xml形式提供数据

RESTAPI默认返回xml数据,如果标头内容类型为application/json,则返回json

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

但是我不知道,如何使用get_response method设置标头来获取json数据。

使用实例方法修改get请求的标头

需要“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'})
数据=resp.body
放置数据

您只需执行以下操作:

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

获取此错误C:\Ruby193>test1.rb C:/Ruby193/test1.rb:4:语法错误,意外的“:”,应为tASSOC…query.to_s}“,{'Content-Type':'application/json'})…^C:/Ruby193/test1.rb:4:语法错误,意外“}”,应为$end…帐篷类型“:'application/json'}”)。^@oecprashant抱歉,这是键入代码时出现的哈希语法错误。我已更新了答案。感谢您的编辑,并让它更清楚。@rubyloveli在上一次访问时遇到此错误行:NoMethodError-未定义的#的方法“[]”:
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
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)