Search code examples
rubyuriopen-uri

URI::InvalidURIError while trying to download by URL with square brackets


I am currently trying to download the picture of this link:

http://z.mfcdn.net/store/manga/9/14-116.0/compressed/Bleach-14-116[manga-rain]._manga_rain_bleach_ch116_01.jpg

This generates a URI::InvalidURIError exception.

After reading around on Stack Overflow, I've tried ( but failed ):

uri = URI.parse(URI.encode(url.strip))

safeurl = URI.encode(url.strip)

I do know the issue has something to do with web browsers being more "friendly" but I do not know how to get my application to do the same.


Solution

  • Here's a sort of hack way of dealing with the invalid characters in the URL:

    u = 'http://z.mfcdn.net/store/manga/9/14-116.0/compressed/Bleach-14-116[manga-rain]._manga_rain_bleach_ch116_01.jpg'
    fixed = u.gsub(/[\[\]]/) { '%%%s' % $&.ord.to_s(16) }
    
    open(fixed)
    

    That should deal with this particular problem.