【问题标题】:tutorialspoint's simple web browser using tcpsockettutorialspoint 使用 tcpsocket 的简单网络浏览器
【发布时间】:2016-12-12 05:37:54
【问题描述】:

这段代码应该可以获取任何网页的内容:

require 'socket'

host = 'www.tutorialspoint.com'     # The web server
port = 80                           # Default HTTP port
path = "/index.htm"                 # The file we want 

# This is the HTTP request we send to fetch a file
request = "GET #{path} HTTP/1.0\r\n\r\n"

socket = TCPSocket.open(host,port)  # Connect to server
socket.print(request)               # Send request
response = socket.read              # Read complete response
# Split response at first blank line into headers and body
headers,body = response.split("\r\n\r\n", 2) 
puts headers
puts body                          

当我在命令行中运行它时,我得到一个 404 错误,但是当我去 www.tutorialspoint.com/index.htm 时它就在那里,那是什么?:

404 Error Information

虽然,我使用 open-uri 库来获取网页内容没有问题。不过我想知道这个怎么用。

【问题讨论】:

    标签: ruby tcpsocket


    【解决方案1】:

    您的请求缺少 Host 参数:

    host = 'www.tutorialspoint.com'     # The web server
    port = 80                           # Default HTTP port
    path = "/index.htm"                 # The file we want 
    
    # This is the HTTP request we send to fetch a file
    request = "GET #{path} HTTP/1.0\r\nHost: #{host}\r\n\r\n"
    

    请注意,显然并非所有网络服务器都需要“Host:”行(但请参阅 cmets)。

    【讨论】:

    • 成功了,我想知道为什么教程缺少一件关键的事情。谢谢,我会记住有些需要主机线路。
    • 确实,并非所有服务器都需要Host 标头,但是the HTTP protocol standard does require the Host header。具有安全意识的服务器应响应错误 400(错误请求)并在请求未提供 Host 标头时终止连接。
    • @JosefTinagan:也许你应该通知教程网站的所有者/编辑。
    猜你喜欢
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    • 2013-06-24
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    相关资源
    最近更新 更多