Search code examples
rubynet-http

Ruby : Net::HTTP parse adds %0A at end


I'm trying to open a file called test.txt and then import each line in a variable called 'line' and then add it in url file to make request.

require 'net/http'
require 'uri'

puts "Enter URL :-"
gurl = gets.chomp

total = File.foreach('test.txt').count
c=0

while(c < total)
line = IO.readlines("test.txt")[c]
aurl = "#{gurl}/#{line}"
encoded_url = URI.encode(aurl)
url = URI.parse(encoded_url)
puts "\n #{url} \n"
res = Net::HTTP.get_response(url)
puts "\n Response received for #{line} => #{res.code} \n"
c+=1
end

Sample outpute =>

 http://www.example.com/z.php%0A

 Response received for z.php
 => 404

 http://www.example.com/index.php%0A

 Response received for index.php
 => 404

Anyway to escape %0A (Newline) ? All new to ruby


Solution

  • If test.txt has n lines, you read it n+1 times!

    Here's a modified version, which chomp to remove the newline/linefeed character :

    require 'net/http'
    require 'uri'
    
    puts "Enter URL :-"
    gurl = gets.chomp
    
    File.foreach('test.txt') do |line|
      line.chomp!
      aurl = "#{gurl}/#{line}"
      encoded_url = URI.encode(aurl)
      url = URI.parse(encoded_url)
      puts "\n #{url} \n"
      res = Net::HTTP.get_response(url)
      puts "\n Response received for #{line} => #{res.code} \n"
    end