1

我从一个 UDP 套接字得到以下响应:

HTTP/1.1 200 OK
CACHE-CONTROL: max-age=1800
DATE: Thu, 08 Nov 2012 12:32:33 GMT
EXT:
LOCATION: http://192.168.0.100:49153/nmrDescription.xml
SERVER: Windows2000/0.0 UPnP/1.0 PhilipsIntelSDK/1.4 DLNADOC/1.50
X-User-Agent: redsonic
ST: upnp:rootdevice
USN: uuid:F00DBABE-SA5E-BABA-DADA188ED55ED539::upnp:rootdevice

是否有一个库或简单的方法来解析所有这些?

我想得到类似以下的东西:

{
  :cache_control => "max-age=1800"
  :date => "Thu, 08 Nov 2012 12:32:33 GMT"
  :ext => nil
  :location => "http://192.168.0.100:49153/nmrDescription.xml"
  # Etc.
}
4

1 回答 1

2
response.split($/).drop(1).inject({}) do |h, l|
  k, v = l.split(": ", 2)
  h[k.downcase.gsub("-", "_").to_sym] = (v unless v.empty?)
  h
end

# => {
#  :cache_control=>"max-age=1800",
#  :date=>"Thu, 08 Nov 2012 12:32:33 GMT",
#  :ext=>nil,
#  :location=>"http://192.168.0.100:49153/nmrDescription.xml",
#  :server=>"Windows2000/0.0 UPnP/1.0 PhilipsIntelSDK/1.4 DLNADOC/1.50",
#  :x_user_agent=>"redsonic",
#  :st=>"upnp:rootdevice",
#  :usn=>"uuid:F00DBABE-SA5E-BABA-DADA188ED55ED539::upnp:rootdevice"
#}
于 2012-11-08T13:27:55.643 回答