Отправка пользовательских заголовков HTTP с помощью Ruby - PullRequest
0 голосов
/ 22 декабря 2018

Я хочу отправить пользовательские заголовки вместе с HTTP-запросом.Я создал следующее на основе примера в ruby-doc, Net :: HTTP, Задание заголовков , но моя версия не работает с «Сброс соединения по пиру»:

#!/usr/bin/env ruby -w
require 'fileutils'
require 'net/http'
require 'time'

cached_response = 'index.html'                                       # Added
FileUtils.touch(cached_response) unless File.exist?(cached_response) # Added
uri = URI("https://www.apple.com/#{cached_response}")                # Changed
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)

Однако отправкабез пользовательского заголовка работает нормально:

#!/usr/bin/env ruby -w
require 'fileutils'
require 'net/http'
require 'time'

cached_response = 'index.html'
uri = URI("https://www.apple.com/#{cached_response}")
FileUtils.touch(cached_response) unless File.exist?(cached_response)
file = File.stat cached_response

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

res = Net::HTTP.get_response(uri)                                    # Changed

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

Может кто-нибудь объяснить, почему моя реализация примера кода Ruby не работает?

Я добавил подобный код для пары маршрутов Синатры:

get '/test1' do
  uri = URI('https://www.apple.com/index.html')
  req = Net::HTTP::Get.new(uri)
  req['Accept'] = request.env['HTTP_ACCEPT']
  res = Net::HTTP.start(uri.hostname, uri.port) { |h| h.request(req) }
  headers = res.to_hash
  headers.delete('transfer-encoding')
  [res.code.to_i, headers, res.body]
end

затем

get '/test2' do
  uri = URI('https://www.apple.com/index.html')
  res = Net::HTTP.get_response(uri)
  headers = res.to_hash
  headers.delete('transfer-encoding')
  [res.code.to_i, headers, res.body]
end

С / test1, я получаю

curl -iv 'http://localhost:9292/test1'
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 9292 (#0)
> GET /test1 HTTP/1.1
> Host: localhost:9292
> User-Agent: curl/7.54.0
> Accept: */*
> 
< HTTP/1.1 500 Internal Server Error 
HTTP/1.1 500 Internal Server Error 
< Content-Type: text/plain
Content-Type: text/plain
< Content-Length: 5582
Content-Length: 5582
< Server: WEBrick/1.4.2 (Ruby/2.5.0/2018-12-06)
Server: WEBrick/1.4.2 (Ruby/2.5.0/2018-12-06)
< Date: Sat, 22 Dec 2018 16:51:03 GMT
Date: Sat, 22 Dec 2018 16:51:03 GMT
< Connection: Keep-Alive
Connection: Keep-Alive

< 
EOFError: end of file reached
    ...
* Connection #0 to host localhost left intact

С / test2, я получаю

curl -iv 'http://localhost:9292/test2'
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 9292 (#0)
> GET /test2 HTTP/1.1
> Host: localhost:9292
> User-Agent: curl/7.54.0
> Accept: */*
> 
< HTTP/1.1 200 OK 
HTTP/1.1 200 OK 
...
<etc. HTML written to console>

Выглядит какзаголовки запроса идентичны.Те же четыре строки.

Если я добавлю заголовок Accept к команде curl, заголовок Accept запроса изменится, как и ожидалось, для обоих, и оба вернут те же результаты, что и раньше (/ test1: 500; / test2: 200)

curl -iv -H 'Accept: application/json' 'http://localhost:9292/test2'
...
> GET /test2 HTTP/1.1
> Host: localhost:9292
> User-Agent: curl/7.54.0
> Accept: application/json

1 Ответ

0 голосов
/ 23 декабря 2018

Наконец-то разобрался.При настройке HTTP-запроса использование схемы «https» автоматически не включает TLS / SSL.Вы должны сделать это явно перед началом запроса.Вот моя обновленная версия:

#!/usr/bin/env ruby -w
# frozen_string_literal: true

require 'fileutils'
require 'net/http'
require 'time'

cached_response = 'index.html'                                     # Added
FileUtils.touch cached_response unless File.exist? cached_response # Added
uri = URI("https://www.apple.com/#{cached_response}")              # Changed
file = File.stat cached_response

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

http = Net::HTTP.new(uri.hostname, uri.port)                       # Added
http.use_ssl = uri.scheme == 'https'                               # Added
res = http.start { |h| h.request(req) }                            # Changed

if res.is_a?(Net::HTTPSuccess)
  File.open cached_response, 'w' do |io|
    io.write res.body
  end
end
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...