如何使用Net :: HTTP只读取正文的x个字节? [英] How do I read only x number of bytes of the body using Net::HTTP?
问题描述
在阅读网页正文时,Ruby的Net :: HTTP方法似乎全有或全无。我怎么能读到,只是身体的前100个字节?
It seems like the methods of Ruby's Net::HTTP are all or nothing when it comes to reading the body of a web page. How can I read, say, the just the first 100 bytes of the body?
我试图从内容服务器读取,如果请求的文件不可用,则会在响应正文中返回一条简短的错误消息。我需要阅读足够的正文以确定文件是否存在。这些文件非常庞大,所以我不想让整个文件检查文件是否可用。
I am trying to read from a content server that returns a short error message in the body of the response if the file requested isn't available. I need to read enough of the body to determine whether the file is there. The files are huge, so I don't want to get the whole body just to check if the file is available.
推荐答案
你不应该只使用HTTP HEAD
请求(Ruby Net :: HTTP :: Head
方法)来查看是否资源是否存在,只有在收到2xx或3xx响应时才会继续?这假设您的服务器配置为在文档不可用时返回4xx错误代码。我认为这是正确的解决方案。
Shouldn't you just use an HTTP HEAD
request (Ruby Net::HTTP::Head
method) to see if the resource is there, and only proceed if you get a 2xx or 3xx response? This presumes your server is configured to return a 4xx error code if the document is not available. I would argue this was the correct solution.
另一种方法是请求HTTP头并查看结果中的 content-length
标头值:if您的服务器配置正确,您应该能够轻松地分辨短消息和长文档之间的长度差异。另一种方法是:在请求中设置 content-range
标头字段(再次假设服务器的行为正确WRT HTTP规范)。
An alternative is to request the HTTP head and look at the content-length
header value in the result: if your server is correctly configured, you should easily be able to tell the difference in length between a short message and a long document. Another alternative: set the content-range
header field in the request (which again assumes that the server is behaving correctly WRT the HTTP spec).
我不认为在发送GET请求之后解决客户端中的问题是要走的路:到那个时候,网络做得很重提升,你不会真正节省任何浪费的资源。
I don't think that solving the problem in the client after you've sent the GET request is the way to go: by that time, the network has done the heavy lifting, and you won't really save any wasted resources.
参考: http标题定义
这篇关于如何使用Net :: HTTP只读取正文的x个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!