【问题标题】:Ruby TCPSocket / HTTP requestRuby TCPSocket / HTTP 请求
【发布时间】:2011-12-27 22:17:57
【问题描述】:

我刚开始使用 TCPSockets。我只是想获取谷歌主页。这是我的代码:

require 'socket'

host = 'http://www.google.com'
port = 80

s = TCPSocket.open host, port
s.puts "GET / HTTP/1.1\r\n"
s.puts "Host: Firefox"
s.puts "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
s.puts "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"
s.puts "\r\n"

while line = s.gets
  puts line.chop
end


s.close

这会返回:

HTTP/1.1 302 Document has moved
Location: http://92.242.140.29/?nxdomain=http%3A%2F%2Ffirefox&AddInType=2&PlatformInfo=pbrgen

为什么?我的目标是获取谷歌主页的内容。谢谢

【问题讨论】:

    标签: ruby tcpsocket


    【解决方案1】:
    require 'socket'
    
    host = 'www.google.com'
    port = 80
    
    s = TCPSocket.open host, port
    s.puts "GET / HTTP/1.1\r\n"
    s.puts "\r\n"
    
    while line = s.gets
      puts line.chop
    end
    
    s.close
    

    此外,使用真正的 HTTP 客户端将使您的生活变得更加轻松。我喜欢Typhoeus

    【讨论】:

    • 嗨,现在我收到 400 Bad Request 和 html 正文“您的浏览器发送了一个此服务器无法理解的请求”
    • puts 方法添加了一个尾随 \n,这会弄乱请求的格式。改用s.send(msg, 0) 应该可以解决问题。
    【解决方案2】:

    302 status 是一种 HTTP 重定向,但在这里您使用的是 TCP,它是 HTTP 之下的网络层,它不理解重定向(或任何其他 HTTP)。 As this SO post shows,但是,还有其他方法可以请求网页,即使用 OpenURI 库而不是套接字。

    【讨论】: