How to fix bad URI is not URI

prabu picture prabu · Mar 29, 2013 · Viewed 80.4k times · Source

I'm using the ruby version 1.9.3, I like to get host name from the video url below,

I tried with code

require 'uri'
url = "https://ferrari-view.4me.it/view-share/playerp/?plContext=http://ferrari-%201363948628-stream.4mecloud.it/live/ferrari/ngrp:livegenita/manifest.f4m&cartellaConfig=http://ferrari-4me.weebo.it/static/player/config/&cartellaLingua=http://ferrari-4me.weebo.it/static/player/config/&poster=http://pusher.newvision.it:8080/resources/img1.jpg&urlSkin=http://ferrari-4me.weebo.it/static/player/swf/skin.swf?a=1363014732171&method=GET&target_url=http://ferrari-4me.weebo.it/static/player/swf/player.swf&userLanguage=IT&styleTextColor=#000000&autoPlay=true&bufferTime=2&isLive=true&highlightColor=#eb2323&gaTrackerList=UA-23603234-4"  
puts URI.parse(url).host  

it throws an exception URI::InvalidURIError: bad URI(is not URI?):

I tried with encode the URL then parse like below

puts URI.parse(URI.parse(url)).host

it throws an exception same URI::InvalidURIError: bad URI(is not URI?)

But above code works for the below URL.

url = http://www.youtube.com/v/GpQDa3PUAbU?version=3&autohide=1&autoplay=1

How to fix this? any suggestion please. Thanks

Answer

Konrad Szczęśniak picture Konrad Szczęśniak · Mar 29, 2013

This url is not valid, but it works in browser because browser itself is less strict about special characters like :, /, etc.

You should encode your URI first

encoded_url = URI.encode(url)

And then parse it

URI.parse(encoded_url)