2013-04-14 17 views
0

我試圖連接到一個Rails服務器,但我不斷收到響應使用TCPSocket通過Ruby連接到Rails服務器。獲得「需要長度的WEBrick :: HTTPStatus :: LengthRequired」。請幫忙嗎?

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 

任何幫助的方式嗎?

回答

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 
+0

謝謝@SamRuby,對點。 –

相關問題