使用TCPSocket通过Ruby连接到Rails服务器。获取“需要长度的WEBrick :: HTTPStatus :: LengthRequired”

时间:2013-04-14 16:25:10

标签: ruby-on-rails ruby webrick content-length tcpsocket

我正在尝试连接到Rails服务器,但我一直得到的响应是

    Length Required WEBrick::HTTPStatus::LengthRequired 

我正在使用TCPSocket连接服务器。

    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) 

我怀疑它是指定内容长度的方式

    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  

1 个答案:

答案 0 :(得分:0)

空白行终止标题,您需要编写内容长度字节。尝试类似下面的内容(注意第二个\ r \ n的移动和206个空格的放置):

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