---
title: "ruby发送带header的http请求 （Send Custom Headers Ruby Net::HTTP）"
author: "hnus"
date: "2015-04-07T09:16:00Z"
tags: []
slug: "ruby-header-http-send-custom-headers-ruby-net-http"
draft: false
lastmod: "2015-05-11T11:49:41Z"
id: 2210117
url: "https://hnus.iteye.com/blog/2210117"
---

```
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

```rb
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