繁体   English   中英

Ruby HTTP2 GET请求

[英]Ruby HTTP2 GET request

我正在尝试使用Ruby gem http-2向Google发送GET请求。

我直接从示例中提取了代码,并对其进行了一些简化:

require 'http/2'
require 'socket'
require 'openssl'
require 'uri'

uri = URI.parse('http://www.google.com/')
tcp = TCPSocket.new(uri.host, uri.port)
sock = tcp

conn = HTTP2::Client.new
conn.on(:frame) do |bytes|
  # puts "Sending bytes: #{bytes.unpack("H*").first}"
  sock.print bytes
  sock.flush
end
conn.on(:frame_sent) do |frame|
  puts "Sent frame: #{frame.inspect}"
end
conn.on(:frame_received) do |frame|
  puts "Received frame: #{frame.inspect}"
end

stream = conn.new_stream

stream.on(:close) do
  puts 'stream closed'
  sock.close
end

stream.on(:half_close) do
  puts 'closing client-end of the stream'
end

stream.on(:headers) do |h|
  puts "response headers: #{h}"
end

stream.on(:data) do |d|
  puts "response data chunk: <<#{d}>>"
end

head = {
  ':scheme' => uri.scheme,
  ':method' => 'GET',
  ':path' => uri.path
}

puts 'Sending HTTP 2.0 request'
stream.headers(head, end_stream: true)

while !sock.closed? && !sock.eof?
  data = sock.read_nonblock(1024)
  # puts "Received bytes: #{data.unpack("H*").first}"

  begin
    conn << data
  rescue => e
    puts "#{e.class} exception: #{e.message} - closing socket."
    e.backtrace.each { |l| puts "\t" + l }
    sock.close
  end
end

输出为:

Sending HTTP 2.0 request
Sent frame: {:type=>:settings, :stream=>0, :payload=>[[:settings_max_concurrent_streams, 100]]}
Sent frame: {:type=>:headers, :flags=>[:end_headers, :end_stream], :payload=>[[":scheme", "http"], [":method", "GET"], [":path", "/"]], :stream=>1}
closing client-end of the stream

(注意:通过运行实际的示例文件,即ruby client.rb http://www.google.com/ ,您将获得与上述几乎相同的输出)

为什么没有显示响应数据?

诸如google.com之类的公共服务器不支持纯文本格式的HTTP / 2。

您尝试连接到http://google.com ,而实际上应该连接到https://google.com (请注意https方案)。

为此,如果http-2没有为您做的话,您可能需要使用TLS包装TCP套接字(请参见此处的示例)。

另请注意,HTTP / 2需要强大的TLS密码和ALPN,因此请确保您具有OpenSSL的更新版本(至少1.0.2)。

鉴于http-2的作者是HTTP / 2的强大支持者,我想您唯一的问题是您尝试使用明文http而不是https ,并且我希望TLS密码强度和ALPN会得到照顾通过http-2库。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM