ruby-on-railsrubywebrickcontent-lengthtcpsocket

Connect to a Rails Server via Ruby using the TCPSocket. Getting "Length Required WEBrick::HTTPStatus::LengthRequired"


I am trying to connect to a Rails server but the response i keep getting is

    Length Required WEBrick::HTTPStatus::LengthRequired 

I am using TCPSocket to connect to the server.

    require 'socket'  
    host = 'localhost'       
    port = 3000                             
    path = '/books/show'  
    #Path of the controller and action to connect to  
    request = "POST #{path} HTTP/1.0\r\n\r\n " 
    socket = TCPSocket.open(host,port)    
    socket.print(request) 

I suspect its the way that the content-length is specified

    socket.puts "content-length: 206\r\n" 
    #write response from server to html file  
    File.open('test2.html', 'w') do |res|  
      while (response_text = socket.gets)        
        res.puts "#{response_text}"       
      end   
    end  
    socket.close  

Solution

  • A blank line terminates the headers, and you will need to write content-length bytes. Try something like the following (note the movement of the second \r\n and the puts of 206 spaces):

    require 'socket'
    host = 'localhost'
    port = 3000
    path = '/products'
    #Path of the controller and action to connect to
    request = "POST #{path} HTTP/1.0\r\n"
    socket = TCPSocket.open(host,port)
    socket.print(request)
    socket.puts "content-length: 206\r\n\r\n"
    socket.puts ' ' * 206
    #write response from server to html file
    File.open('test2.html', 'w') do |res|
      while (response_text = socket.gets)
        res.puts "#{response_text}"
      end
    end
    socket.close