gpt4 book ai didi

Ruby HTTP2 GET 请求

转载 作者:数据小太阳 更新时间:2023-10-29 08:30:29 24 4
gpt4 key购买 nike

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

我直接从 example 中提取了代码并稍微简化一下:

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 等公共(public)服务器不支持明文形式的 HTTP/2。

您正在尝试连接到 http://google.com , 虽然你真的应该连接到 https://google.com (注意 https 方案)。

为此,您可能需要使用 TLS 包装 TCP 套接字(参见示例 here ),如果 http-2 没有为您完成。

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

鉴于 http-2 的作者是 HTTP/2 的坚定支持者,我猜你唯一的问题是你尝试了明文 http而不是 https,我希望 TLS 密码强度和 ALPN 由 http-2 库处理。

关于Ruby HTTP2 GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39600306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com