0

我正在尝试连接到 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  
4

1 回答 1

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
于 2013-04-14T22:58:18.427 回答