2010-08-13 96 views
2

我正在使用一個Ruby on Rails應用程序來對第三方服務進行客戶端API調用。然後,它從第三方API獲取字符串並使用它們生成URI。解決Rails中的URI字符編碼問題

不幸的是,由於編碼錯誤,Rails無法解析某些URI。我試過通過encodeURIComponent運行字符串,但這不能解決問題。

以下是錯誤我得到:

Processing ApplicationController#index (for 67.101.113.66 at 2010-08-12 23:24:55) [GET] 
    Parameters: {"name"=>"Camilo Andr\xE9s \xD1ustes", "recipient_id"=>"279"} 

ArgumentError (invalid byte sequence in US-ASCII): 
    <internal:prelude>:8:in `synchronize' 
    /home/heroku_rack/lib/static_assets.rb:9:in `call' 
    /home/heroku_rack/lib/last_access.rb:25:in `call' 
    /home/heroku_rack/lib/date_header.rb:14:in `call' 
    thin (1.2.6) lib/thin/connection.rb:76:in `block in pre_process' 
    thin (1.2.6) lib/thin/connection.rb:74:in `catch' 
    thin (1.2.6) lib/thin/connection.rb:74:in `pre_process' 
    thin (1.2.6) lib/thin/connection.rb:57:in `process' 
    thin (1.2.6) lib/thin/connection.rb:42:in `receive_data' 
    eventmachine (0.12.10) lib/eventmachine.rb:256:in `run_machine' 
    eventmachine (0.12.10) lib/eventmachine.rb:256:in `run' 
    thin (1.2.6) lib/thin/backends/base.rb:57:in `start' 
    thin (1.2.6) lib/thin/server.rb:156:in `start' 
    thin (1.2.6) lib/thin/controllers/controller.rb:80:in `start' 
    thin (1.2.6) lib/thin/runner.rb:177:in `run_command' 
    thin (1.2.6) lib/thin/runner.rb:143:in `run!' 
    thin (1.2.6) bin/thin:6:in `<top (required)>' 
    /usr/ruby1.9.1/bin/thin:19:in `load' 

    /usr/ruby1.9.1/bin/thin:19:in `<main>' 

如何正確處理這些字符串作爲輸入我的應用程序?

回答

1

這個工作對我來說:<%= u name -%>

我使用這種技術,每次我不得不四處傳遞身份驗證令牌在我的觀點: <%= u form_authenticity_token %>

由於上述是對的看法,如果你想紅寶石具體:

require 'uri' 
foo = "http://google.com?query=hello" 

bad = URI.escape(foo) 
good = URI.escape(foo, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]")) 

bad_uri = "http://mysite.com?service=#{bad}&bar=blah" 
good_uri = "http://mysite.com?service=#{good}&bar=blah" 

puts bad_uri 
# outputs "http://mysite.com?service=http://google.com?query=hello&bar=blah" 

puts good_uri 
# outputs "http://mysite.com?service=http%3A%2F%2Fgoogle.com%3Fquery%3Dhello&bar=blah" 

希望這會有所幫助。

+0

謝謝。如果這是解決方案,但是,我需要在JavaScript中完成。 該名稱來自jsonp api調用,然後附加到該url。 我現在的解決方案是將應用程序切換到使用Ruby 1.8而不是1.9。 – Gdeglin 2010-08-19 20:45:43

+0

即使它來自jsonp api調用,我猜你正在控制器的操作中接收它爲'params [:name]','params [:recepient_id]'對嗎?爲什麼不只是'URI.escape(params [:name],Regexp.new(「[^#{URI :: PATTERN :: UNRESERVED}]」))'?我從日誌輸出中看到您正在接收參數..只是在存儲/操作數據之前將其轉義。如果您可以提供控制器操作的瘦身版本,那麼提供解決方案會更容易。 – 2010-08-20 02:28:58

+0

這是一個jsonp API調用,這是所有完成客戶端。數據然後被髮送到軌道控制器。它在Rack內部失效之前甚至會觸發控制器操作。 – Gdeglin 2010-08-27 22:11:48