Sanjay Salunkhe Sanjay Salunkhe - 5 months ago 22
Ruby Question

Ruby Telnet: How to send http request using telnet

I am using ruby telnet library to make HTTP get request(http://127.0.0.1:3000/test) but i am not able to make http get request to my server.

Below is the code that i am trying

require 'net/telnet'
webserver = Net::Telnet::new('Host' => '127.0.0.1', 'Port' => 3000, 'Telnetmode' => false)
size = 0
webserver.cmd("GET / HTTP/1.1\nHost: 127.0.0.1/test") do |c|
print c
end


Please let me know what wrong i am doing here.

Answer

You need to end your input HTTP with a carriage return and line ending, otherwise the HTTP server will wait for more headers:

webserver.cmd("GET /test HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n") do |c|
  print c
end

But telnet really isn't the right thing to use (unless you're just experimenting). If you want to make HTTP requests for a real-world program, you should definitely use a proper HTTP library (net/http at the least, or something like Faraday would be even better). HTTP seems simple, but there are many hidden complexities that mean creating a writer/parser from scratch is a lot of work.

Comments