2011-02-15 72 views
3

我試圖從URL下載HTML內容而沒有成功。使用Ruby轉義和下載URL

這裏是網址:

http://example.com/some_string[value] 

當使用RESTClient實現我得到這個錯誤:

URI::InvalidURIError: bad URI(is not URI?) 

我從Ruby on Rails的IRC一些幫助。這個想法是爲了逃避URL的結束。

$ "http://example.com/" + CGI::escape("some_string[value]") 
=> "http://example.com/some_string%5Bvalue%5D" 

生成的URL不工作,我得到一個404 它可以在瀏覽器雖然。

任何人都知道如何讓它工作?

回答

2

按照URI RFC

Other characters are excluded because gateways and other transport agents are known to sometimes modify such characters, or they are used as delimiters.

unwise = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`"

Data corresponding to excluded characters must be escaped in order to be properly represented within a URI.

信任瀏覽器的反應或處理能力的鏈接是有風險的。他們盡其所能地返回頁面,而不是強制執行標準,因此無論頁面或URL是否被正確定義,它們都不是權威來源。

RestClient的響應可能基於URI,當我測試使用URI解析URL時,它返回相同的錯誤。

我從未見過使用未編碼「[」和「]」字符的URL。

+0

謝謝,工作完美。我用這個來逃避網址。 `url.gsub(/ \ {| \} | \ || \\ | \^| \ [| \] | \`| \ s + /){| m | CGI :: escape(m)}`我躲過了正則表達式中的每個字符,以防萬一:) – Oleander 2011-02-17 23:27:00