0

我有一些我的 Ruby/Rails (Ruby 2.0.0p195, Rails 3.2.13) 项目可以作为代理;也就是说,您向它传递一个 URL,它会出去并获取页面,并将其呈现给您。这通常可以按预期工作,但似乎可以处理某些字符(例如 è)。

控制器的简化版本是这样的:

class HomeController < ApplicationController
  def geoproxy
    require 'net/http'
    require 'timeout'

    rawurl = CGI::unescape(params[:url])

    fixedurl = rawurl.gsub('\\', '%5C')   # Escape backslashes... why oh why???!?
    r = nil;

    status = 200
    content_type = ''

    begin
      Timeout::timeout(15) {        # Time, in seconds

        if request.get? then
          res = Net::HTTP.get_response(URI.parse(fixedurl))

          status = res.code    # If there was an  error, pass that code back to our caller
          @page = res.body.encode('UTF-8')
          content_type = res['content-type']    
        end
      }

    rescue Timeout::Error
      @page = "TIMEOUT"
      status = 504    # 504 Gateway Timeout  We're the gateway, we timed out.  Seems logical.
    end

    render :layout => false, :status => status, :content_type => content_type
  end
end

对应的视图很简单:

<%= raw @page %>

当我使用此代理获取包含 è 的 XML(例如)时,我收到以下错误:

Encoding::UndefinedConversionError in HomeController#geoproxy
"\xE8" from ASCII-8BIT to UTF-8

此错误发生在以下行:

@page = res.body.encode('UTF-8')

如果我删除 .encode(),则错误得到解决,但我的 XML 包含占位符而不是 è。

如何让我的项目正确显示 XML?

4

1 回答 1

1

您能否检查以下代码是否适合您?我能够用它解决我的类似问题。

@page = res.body.force_encoding('Windows-1254').encode('UTF-8')
于 2013-07-17T12:35:57.140 回答