Ruby TCPSocket/HTTP请求 [英] Ruby TCPSocket / HTTP request

查看:117
本文介绍了Ruby TCPSocket/HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用TCPSockets.我只是想获得Google主页.这是我的代码:

I just started with TCPSockets. I am simply trying to get the google home page. This is my code:

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主页的内容.谢谢

Why? My goal is to get the contents of google home page. Thanks

推荐答案

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 .

Also, using a real HTTP client will make your life much, much easier. I like Typhoeus.

这篇关于Ruby TCPSocket/HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆