【问题标题】:how to set header['content-type']='application/json' in ruby如何在 ruby​​ 中设置 header['content-type']='application/json'
【发布时间】:2013-04-07 04:49:56
【问题描述】:
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 方法设置标头。获取 json 数据。

【问题讨论】:

  • 感谢您的编辑,并使其更加清晰。 @rubylovely

标签: ruby rest net-http


【解决方案1】:

使用实例方法Net::HTTP#get修改GET请求的头部。

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

【讨论】:

  • 收到此错误 C:\Ruby193>test1.rb C:/Ruby193/test1.rb:4: 语法错误,意外 ':',期待 tASSOC ....query.to_s}", {'Content-Type': 'application/json'}) ... ^ C:/Ruby193/test1.rb:4: 语法错误,意外'}',期待 $end ...tent-Type': 'application /json'}) ... ^
  • @oecprashant 抱歉,输入代码时出现哈希语法错误。我已经更新了答案。
【解决方案2】:
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

【讨论】:

    【解决方案3】:

    你可以这样做:

    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)
    

    【讨论】:

    • 我在你的最后一行出现了这个错误:NoMethodError - undefined method `[]' for #<:http:0x007ff0bf8b47c0>:
    猜你喜欢
    • 1970-01-01
    • 2017-11-06
    • 2018-03-17
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2012-05-22
    相关资源
    最近更新 更多