获得从路边响应头(Get response headers from Curb)

2019-07-18 06:18发布

我打算从on Rails应用程序一个Ruby的电话:

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

响应应具有自定义标题:

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

如何遍历响应头的值进行比较,以我所期待的?

Answer 1:

使用curl ::简单的header_str可以访问返回的标题为字符串。 从文档:

从上一次调用执行返回的响应头。 这是由默认on_header处理填充 - 若你提供你自己的头的处理程序,这个字符串将是空的。

为了测试这个我打开内置的使用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"
    }

再次测试,在撬:

[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"
}


文章来源: Get response headers from Curb
标签: ruby curb