gpt4 book ai didi

ruby - 从 Curb 获取响应头

转载 作者:数据小太阳 更新时间:2023-10-29 06:42:34 26 4
gpt4 key购买 nike

我打算从 Ruby on Rails 应用程序进行调用:

c = Curl::Easy.http_post("https://example.com", json_string_goes_here) do |curl|
curl.headers['Accept'] = 'application/json'
curl.headers['Content-Type'] = 'application/json'
curl.headers['Api-Version'] = '2.2'
end

响应应该有自定义 header :

X-Custom1 : "some value"
X-Custom2 : "another value"

我如何遍历响应 header 以将值与我期望的值进行比较?

最佳答案

使用 Curl::Easy 的 header_str,您可以访问作为字符串返回的 header 。来自文档:

Return the response header from the previous call to perform. This is populated by the default on_header handler - if you supply your own header handler, this string will be empty.

为了测试这一点,我使用以下命令打开了内置的 Gem 服务器:

gem server

下面是一些测试代码:

curl = Curl::Easy.http_get('http://0.0.0.0:8808')
curl.header_str
=> "HTTP/1.1 200 OK \r\nDate: 2013-01-10 09:07:42 -0700\r\nContent-Type: text/html\r\nServer: WEBrick/1.3.1 (Ruby/1.9.3/2012-11-10)\r\nContent-Length: 62164\r\nConnection: Keep-Alive\r\n\r\n"

捕获响应并将剩余的字符串分解成散列以使其更易于使用,这很简单:

http_response, *http_headers = curl.header_str.split(/[\r\n]+/).map(&:strip)
http_headers = Hash[http_headers.flat_map{ |s| s.scan(/^(\S+): (.+)/) }]

http_response # => "HTTP/1.1 200 OK"

http_headers
=> {
"Date" => "2013-01-10 09:07:42 -0700",
"Content-Type" => "text/html",
"Server" => "WEBrick/1.3.1 (Ruby/1.9.3/2012-11-10)",
"Content-Length" => "62164",
"Connection" => "Keep-Alive"
}

再次测试,在 Pry 中:

[27] (pry) main: 0> curl = Curl::Easy.http_get('http://www.example.com')
#<Curl::Easy http://www.example.com>
[28] (pry) main: 0> curl.header_str
"HTTP/1.0 302 Found\r\nLocation: http://www.iana.org/domains/example/\r\nServer: BigIP\r\nConnection: Keep-Alive\r\nContent-Length: 0\r\n\r\n"
[29] (pry) main: 0> http_response, *http_headers = curl.header_str.split(/[\r\n]+/).map(&:strip)
[
[0] "HTTP/1.0 302 Found",
[1] "Location: http://www.iana.org/domains/example/",
[2] "Server: BigIP",
[3] "Connection: Keep-Alive",
[4] "Content-Length: 0"
]
[30] (pry) main: 0> http_headers = Hash[http_headers.flat_map{ |s| s.scan(/^(\S+): (.+)/) }]
{
"Location" => "http://www.iana.org/domains/example/",
"Server" => "BigIP",
"Connection" => "Keep-Alive",
"Content-Length" => "0"
}

关于ruby - 从 Curb 获取响应头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14345805/

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