簡體   English   中英

Ruby TCPSocket / HTTP 請求

[英]Ruby TCPSocket / HTTP request

我剛開始使用 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

為什么? 我的目標是獲取谷歌主頁的內容。 謝謝

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

302 狀態是一種 HTTP 重定向,但在這里您使用的是 TCP,它是 HTTP 下的一個網絡層,它不理解重定向(或任何其他 HTTP)。 但是,正如這篇 SO 帖子所示,還有其他方法可以請求網頁,即使用 OpenURI 庫而不是套接字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM