URI with variable

2019-08-05 11:56发布

问题:

I've got a file with uids on separate lines, and I'm trying to include them in a URI.

File.open("File Path").readlines.each do |line|

puts line

uid = line 

uri = URI("http://example:port/path/variable=#{uid}&fragment")

res = Net::HTTP.get_response(uri)

puts res.body

But I get an error saying "bad URI(is not URI?)".

Could anyone help?

Thanks

回答1:

Can you try a

uid = line.strip

The strip removes leading and trailing spaces and newlines.

With

p uid

or

puts uid.inspect

you may see the real content of the string.



回答2:

It depends a lot on what are you actually feeding it, but I recommend trying these 2 things so you troubleshoot your code well.

  • Use puts "[#{uid}]" to see what does the line variable contain exactly. This will surely help you notice if it has a newline in it, for example. The right square bracket will be on the next line and you will know your input is malformed.

  • Try constructing the URL like this: uri = URI("http://example:port/path/variable=#{URI.encode(uid)}&fragment"). This will help you escape characters which are normally not allowed in an URI / URL.

Hope this helps.



回答3:

do you means

uri = URI("http://example:port/path/?variable=#{uid}&fragment")


标签: ruby file uri