对ruby的漂亮打印webservice响应

时间:2013-11-19 13:00:14

标签: ruby-on-rails ruby xml json format

我有一个非常奇怪的要求。

我必须调用webservice,但我不知道响应的格式。在任何情况下(xml,json或html)我都要打印响应。

例如,如果它是一个xml我必须缩进并正确显示它。同样的事情,如果它是一个json。我有两个问题:

  1. 检测格式
  2. 根据类型应用格式。
  3. 我认为(1)是最具挑战性的问题。

    有任何帮助吗?

2 个答案:

答案 0 :(得分:3)

正如其中一些评论所暗示的那样,http标头将包含内容类型。

net / http有以下方法:http://ruby-doc.org/stdlib-2.0.0/libdoc/net/http/rdoc/Net/HTTP.html#method-i-head

require 'net/http'
require 'json'
require 'rexml/document'

response = nil
Net::HTTP.start('www.google.com', 80) {|http|
  response = http.get('/index.html')
}
header = response['content-type'].split(';').first  # => "text/html"
body = response.read_body

然后你可以有条件地操作:

if header == "text/html"
  puts response.read_body
elsif header == "application/json"
  puts JSON.pretty_generate(JSON.parse(body))
elsif header == "text/xml"
  xml = REXML::Document.new body
  out = ""
  xml.write(out, 1)
  puts out
end

大部分内容都来自其他SO帖子:

漂亮的JSON:How can I "pretty" format my JSON output in Ruby on Rails?

漂亮的XML:How to beautify xml code in rails application

答案 1 :(得分:0)

这是我最终使用的代码:

      raw_response = response.body
      response_html = ''

      if response.header['Content-Type'].include? 'application/json'
        tokens = CodeRay.scan(raw_response, :json)
        response_html = tokens.div
      elsif response.header['Content-Type'].include? 'application/xml'
        tokens = CodeRay.scan(raw_response, :xml)
        response_html = tokens.div
      elsif response.header['Content-Type'].include? 'text/html'
        tokens = CodeRay.scan(raw_response, :html)
        response_html = tokens.div
      else
        response_html = '<div>' + raw_response + '</div>'
      end

它正在使用'coderay'宝石。