ruby发送带header的http请求 (Send Custom Headers Ruby Net::HTTP)

本文介绍了如何使用 Ruby 的 Net::HTTP 库进行 HTTP GET 请求,并通过修改请求头来实现条件 GET 请求及分块下载功能。文章展示了如何设置 If-Modified-Since 和 Range 请求头,以减少带宽消耗和提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



uri = URI('http://example.com/cached_response')
file = File.stat 'cached_response'

req = Net::HTTP::Get.new(uri)
req['If-Modified-Since'] = file.mtime.rfc2822

res = Net::HTTP.start(uri.hostname, uri.port) {|http|
  http.request(req)
}

open 'cached_response', 'w' do |io|
  io.write res.body
end if res.is_a?(Net::HTTPSuccess)

require "net/http"require "uri"url = URI.parse("http://www.whatismyip.com/automation/n09230945.asp")req = Net::HTTP::Get.new(url.path)req.add_field("X-Forwarded-For", "0.0.0.0")res = Net::HTTP.new(url.host, url.port).start do |http| http.request(req)endputs res.body

http://stackoverflow.com/questions/587559/how-to-make-an-http-get-with-modified-headers

require 'uri'
require 'net/http'

size = 1000 #the last offset (for the range header)
uri = URI("http://localhost:80/index.html")
http = Net::HTTP.new(uri.host, uri.port)
headers = {
    'Range' => "bytes=#{size}-"
}
path = uri.path.empty? ? "/" : uri.path

#test to ensure that the request will be valid - first get the head
code = http.head(path, headers).code.to_i
if (code >= 200 && code < 300) then

    #the data is available...
    http.get(uri.path, headers) do |chunk|
        #provided the data is good, print it...
        print chunk unless chunk =~ />416.+Range/
    end
end


http://ruby-doc.org/stdlib-2.1.1/libdoc/net/http/rdoc/Net/HTTP.html



http://stackoverflow.com/questions/587559/how-to-make-an-http-get-with-modified-headers
http://ruby-doc.org/stdlib-2.1.1/libdoc/net/http/rdoc/Net/HTTP.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值