【问题标题】:Pretty print webservice response on rubyruby 上的漂亮打印 web 服务响应
【发布时间】:2013-12-03 01:07:17
【问题描述】:

我有一个很好奇的需求。

我必须调用网络服务,但我不知道响应的格式。在任何情况下(xml、json 或 html)我都必须漂亮地打印响应。

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

  1. 检测格式
  2. 根据类型应用格式。

我认为(1)是最具挑战性的问题。

有什么帮助吗?

【问题讨论】:

  • 解析为json并假设如果失败,它将是html,但我不确定这种方法
  • 能否附上你用过的代码?
  • 检查响应的 Content-Type 标头。它可能类似于text/htmlapplication/jsonapplication/xml(但可以是其他类型)。
  • 从 webservice 解析响应头 Content-Type

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


【解决方案1】:

正如一些 cmets 所建议的,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

【讨论】:

    【解决方案2】:

    这是我最后使用的代码:

          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”gem。

    【讨论】:

      猜你喜欢
      • 2012-05-08
      • 2011-01-07
      • 2011-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      • 2018-09-08
      相关资源
      最近更新 更多