无效的 URI - 如何防止 URI::InvalidURIError 错误? [英] invalid URI - How to prevent, URI::InvalidURIError errors?
问题描述
我从 delay_job 得到以下回复:
I got the following back from delayed_job:
[Worker(XXXXXX pid:3720)] Class#XXXXXXX failed with URI::InvalidURIError: bad URI(is not URI?): https://s3.amazonaws.com/cline-local-dev/2/attachments/542/original/mac-os-x[1].jpeg?AWSAccessKeyId=xxxxxxxx&Expires=1295403309&Signature=xxxxxxx%3D - 3 failed attempts
这个 URI 在我的应用程序中的来源.
The way this URI comes from in my app is.
在我的 user_mailer 中:
In my user_mailer I do:
@comment.attachments.each do |a|
attachments[a.attachment_file_name] = open(a.authenticated_url()) {|f| f.read }
end
然后在我的附件模型中:
Then in my attachments model:
def authenticated_url(style = nil, expires_in = 90.minutes)
AWS::S3::S3Object.url_for(attachment.path(style || attachment.default_style), attachment.bucket_name, :expires_in => expires_in, :use_ssl => attachment.s3_protocol == 'https')
end
话虽如此,是否有某种类型的 URI.encode 或解析我可以做来防止有效的 URI(因为我检查了 URL 在我的浏览器中有效)以防止在 rails 3 中出错和杀死 delay_job?
That being said, is there some type of URI.encode or parsing I can do to prevent a valid URI (as I checked the URL works in my browser) for erroring and killing delayed_job in rails 3?
谢谢!
推荐答案
Ruby 有(至少)两个模块来处理 URI.
Ruby has (at least) two modules for dealing with URIs.
URI 是标准库的一部分.
Addressable::URI,是一个单独的 gem,更全面,并声称符合规范.
Addressable::URI, is a separate gem, and more comprehensive, and claims to conform to the spec.
使用其中之一解析 URL,使用 gem 的方法修改任何参数,然后在传递之前使用 to_s
将其转换,您应该很高兴.
Parse a URL with either one, modify any parameters using the gem's methods, then convert it using to_s
before passing it on, and you should be good to go.
我试过' open( URI.parse(URI.encode( a.authenticated_url() )) '但错误OpenURI::HTTPError: 403 Forbidden
I tried ' open( URI.parse(URI.encode( a.authenticated_url() )) ' but that errord with OpenURI::HTTPError: 403 Forbidden
如果您通过浏览器导航到该页面并成功,然后通过代码直接访问该页面失败,则可能缺少 cookie 或会话状态.您可能需要使用类似 Mechanize 之类的东西,这将保持该状态,同时允许您浏览网站.
If you navigated to that page via a browser and it succeeded, then later failed going to it directly via code, it's likely there is a cookie or session state that is missing. You might need to use something like Mechanize, which will maintain that state while allowing you to navigate through a site.
require 'addressable/uri'
url = 'http://www.example.com'
uri = Addressable::URI.parse(url)
uri.query_values = {
:foo => :bar,
:q => '"one two"'
}
uri.to_s # => "http://www.example.com?foo=bar&q=%22one%20two%22"
这篇关于无效的 URI - 如何防止 URI::InvalidURIError 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!