我刚开始使用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为什么?我的目标是获取google主页的内容。谢谢
发布于 2011-12-28 06:23:21
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。
发布于 2011-12-28 06:25:43
302 status是一种超文本传输协议重定向,但这里使用的是TCP,它是位于超文本传输协议之下的网络层,它不理解重定向(或任何其他超文本传输协议)。As this SO post shows,然而,还有其他方法来请求网页,即使用OpenURI库而不是套接字。
https://stackoverflow.com/questions/8649860
复制相似问题