gpt4 book ai didi

ruby - 如何使用 Net::HTTP 只读取正文的 x 个字节?

转载 作者:数据小太阳 更新时间:2023-10-29 06:40:29 25 4
gpt4 key购买 nike

在读取网页正文时,Ruby 的 Net::HTTP 方法似乎是全有或全无。例如,我如何读取正文的前 100 个字节?

如果请求的文件不可用,我正在尝试从内容服务器读取内容服务器,该内容服务器会在响应正文中返回一条简短的错误消息。我需要阅读足够多的正文以确定文件是否存在。文件很大,所以我不想让整个 body 只是为了检查文件是否可用。

最佳答案

这是一个旧线程,但根据我的研究,如何在 Ruby 中通过 HTTP 只读取文件的一部分的问题仍然是一个大部分没有答案的问题。这是我通过猴子修补 Net::HTTP 得到的一个解决方案:

require 'net/http'

# provide access to the actual socket
class Net::HTTPResponse
attr_reader :socket
end

uri = URI("http://www.example.com/path/to/file")
begin
Net::HTTP.start(uri.host, uri.port) do |http|
request = Net::HTTP::Get.new(uri.request_uri)
# calling request with a block prevents body from being read
http.request(request) do |response|
# do whatever limited reading you want to do with the socket
x = response.socket.read(100);
# be sure to call finish before exiting the block
http.finish
end
end
rescue IOError
# ignore
end

救援捕获当您过早调用 HTTP.finish 时抛出的 IOError。

仅供引用,HTTPResponse 对象中的套接字不是真正的 IO 对象(它是一个名为 BufferedIO 的内部类),但它是猴子补丁也很容易模仿你需要的 IO 方法。例如,我使用的另一个库 (exifr) 需要 readchar 方法,这很容易添加:

class Net::BufferedIO
def readchar
read(1)[0].ord
end
end

关于ruby - 如何使用 Net::HTTP 只读取正文的 x 个字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/82349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com