首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Curb获取响应标头

从Curb获取响应标头
EN

Stack Overflow用户
提问于 2013-01-15 19:58:31
回答 1查看 6.3K关注 0票数 13

我打算从Rails应用程序中调用:

代码语言:javascript
复制
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

响应应该具有自定义标头:

代码语言:javascript
复制
X-Custom1 : "some value"
X-Custom2 : "another value"

如何在响应头上迭代以将值与我所期望的值进行比较?

EN

回答 1

Stack Overflow用户

发布于 2013-01-16 07:08:48

使用Curl::Easy的header_str,您可以以字符串的形式访问返回的头部。从文件中:

从上一次调用返回要执行的响应头。这由默认的on_header处理程序填充--如果提供自己的头处理程序,则此字符串将为空。

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

代码语言:javascript
复制
gem server

下面是一些测试这个的代码:

代码语言:javascript
复制
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"

捕获响应,并将剩下的字符串分解为哈希,使其更易于使用,非常简单:

代码语言:javascript
复制
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"
    }

再次测试,以撬:

代码语言:javascript
复制
[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"
}
票数 36
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14345805

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档