Module Net::HTTPHeader
In: lib/net/http.rb

Header module.

Provides access to @header in the mixed-into class as a hash-like object, except with case-insensitive keys. Also provides methods for accessing commonly-used header values in a more convenient format.

Methods

External Aliases

size -> length

Public Instance methods

Returns the header field corresponding to the case-insensitive key. For example, a key of "Content-Type" might return "text/html"

[Source]

      # File lib/net/http.rb, line 1154
1154:     def [](key)
1155:       a = @header[key.downcase] or return nil
1156:       a.join(', ')
1157:     end

Sets the header field corresponding to the case-insensitive key.

[Source]

      # File lib/net/http.rb, line 1160
1160:     def []=(key, val)
1161:       unless val
1162:         @header.delete key.downcase
1163:         return val
1164:       end
1165:       @header[key.downcase] = [val]
1166:     end

[Ruby 1.8.3] Adds header field instead of replace. Second argument val must be a String. See also #[]=, #[] and get_fields.

  request.add_field 'X-My-Header', 'a'
  p request['X-My-Header']              #=> "a"
  p request.get_fields('X-My-Header')   #=> ["a"]
  request.add_field 'X-My-Header', 'b'
  p request['X-My-Header']              #=> "a, b"
  p request.get_fields('X-My-Header')   #=> ["a", "b"]
  request.add_field 'X-My-Header', 'c'
  p request['X-My-Header']              #=> "a, b, c"
  p request.get_fields('X-My-Header')   #=> ["a", "b", "c"]

[Source]

      # File lib/net/http.rb, line 1183
1183:     def add_field(key, val)
1184:       if @header.key?(key.downcase)
1185:         @header[key.downcase].push val
1186:       else
1187:         @header[key.downcase] = [val]
1188:       end
1189:     end

Set the Authorization: header for "Basic" authorization.

[Source]

      # File lib/net/http.rb, line 1439
1439:     def basic_auth(account, password)
1440:       @header['authorization'] = [basic_encode(account, password)]
1441:     end
canonical_each()

Alias for each_capitalized

Returns "true" if the "transfer-encoding" header is present and set to "chunked". This is an HTTP/1.1 feature, allowing the the content to be sent in "chunks" without at the outset stating the entire content length.

[Source]

      # File lib/net/http.rb, line 1350
1350:     def chunked?
1351:       return false unless @header['transfer-encoding']
1352:       field = self['Transfer-Encoding']
1353:       (/(?:\A|[^\-\w])chunked(?![\-\w])/i =~ field) ? true : false
1354:     end

Returns an Integer object which represents the Content-Length: header field or nil if that field is not provided.

[Source]

      # File lib/net/http.rb, line 1331
1331:     def content_length
1332:       return nil unless key?('Content-Length')
1333:       len = self['Content-Length'].slice(/\d+/) or
1334:           raise HTTPHeaderSyntaxError, 'wrong Content-Length format'
1335:       len.to_i
1336:     end

[Source]

      # File lib/net/http.rb, line 1338
1338:     def content_length=(len)
1339:       unless len
1340:         @header.delete 'content-length'
1341:         return nil
1342:       end
1343:       @header['content-length'] = [len.to_i.to_s]
1344:     end

Returns a Range object which represents Content-Range: header field. This indicates, for a partial entity body, where this fragment fits inside the full entity body, as range of byte offsets.

[Source]

      # File lib/net/http.rb, line 1359
1359:     def content_range
1360:       return nil unless @header['content-range']
1361:       m = %r<bytes\s+(\d+)-(\d+)/(\d+|\*)>i.match(self['Content-Range']) or
1362:           raise HTTPHeaderSyntaxError, 'wrong Content-Range format'
1363:       m[1].to_i .. m[2].to_i + 1
1364:     end

Returns a content type string such as "text/html". This method returns nil if Content-Type: header field does not exist.

[Source]

      # File lib/net/http.rb, line 1374
1374:     def content_type
1375:       return nil unless main_type()
1376:       if sub_type()
1377:       then "#{main_type()}/#{sub_type()}"
1378:       else main_type()
1379:       end
1380:     end
content_type=(type, params = {})

Alias for set_content_type

Removes a header field.

[Source]

      # File lib/net/http.rb, line 1246
1246:     def delete(key)
1247:       @header.delete(key.downcase)
1248:     end
each(

Alias for each_header

As for each_header, except the keys are provided in capitalized form.

[Source]

      # File lib/net/http.rb, line 1261
1261:     def each_capitalized
1262:       @header.each do |k,v|
1263:         yield capitalize(k), v.join(', ')
1264:       end
1265:     end

Iterates for each capitalized header names.

[Source]

      # File lib/net/http.rb, line 1232
1232:     def each_capitalized_name(&block)   #:yield: +key+
1233:       @header.each_key do |k|
1234:         yield capitalize(k)
1235:       end
1236:     end

Iterates for each header names and values.

[Source]

      # File lib/net/http.rb, line 1216
1216:     def each_header   #:yield: +key+, +value+
1217:       @header.each do |k,va|
1218:         yield k, va.join(', ')
1219:       end
1220:     end
each_key()

Alias for each_name

Iterates for each header names.

[Source]

      # File lib/net/http.rb, line 1225
1225:     def each_name(&block)   #:yield: +key+
1226:       @header.each_key(&block)
1227:     end

Iterates for each header values.

[Source]

      # File lib/net/http.rb, line 1239
1239:     def each_value   #:yield: +value+
1240:       @header.each_value do |va|
1241:         yield va.join(', ')
1242:       end
1243:     end

Returns the header field corresponding to the case-insensitive key. Returns the default value args, or the result of the block, or nil, if there‘s no header field named key. See Hash#fetch

[Source]

      # File lib/net/http.rb, line 1210
1210:     def fetch(key, *args, &block)   #:yield: +key+
1211:       a = @header.fetch(key.downcase, *args, &block)
1212:       a.join(', ')
1213:     end
form_data=(params, sep = '&')

Alias for set_form_data

[Ruby 1.8.3] Returns an array of header field strings corresponding to the case-insensitive key. This method allows you to get duplicated header fields without any processing. See also #[].

  p response.get_fields('Set-Cookie')
    #=> ["session=al98axx; expires=Fri, 31-Dec-1999 23:58:23",
         "query=rubyscript; expires=Fri, 31-Dec-1999 23:58:23"]
  p response['Set-Cookie']
    #=> "session=al98axx; expires=Fri, 31-Dec-1999 23:58:23, query=rubyscript; expires=Fri, 31-Dec-1999 23:58:23"

[Source]

      # File lib/net/http.rb, line 1202
1202:     def get_fields(key)
1203:       return nil unless @header[key.downcase]
1204:       @header[key.downcase].dup
1205:     end

[Source]

      # File lib/net/http.rb, line 1137
1137:     def initialize_http_header(initheader)
1138:       @header = {}
1139:       return unless initheader
1140:       initheader.each do |key, value|
1141:         warn "net/http: warning: duplicated HTTP header: #{key}" if key?(key) and $VERBOSE
1142:         @header[key.downcase] = [value.strip]
1143:       end
1144:     end

true if key header exists.

[Source]

      # File lib/net/http.rb, line 1251
1251:     def key?(key)
1252:       @header.key?(key.downcase)
1253:     end

Returns a content type string such as "text". This method returns nil if Content-Type: header field does not exist.

[Source]

      # File lib/net/http.rb, line 1384
1384:     def main_type
1385:       return nil unless @header['content-type']
1386:       self['Content-Type'].split(';').first.to_s.split('/')[0].to_s.strip
1387:     end

Set Proxy-Authorization: header for "Basic" authorization.

[Source]

      # File lib/net/http.rb, line 1444
1444:     def proxy_basic_auth(account, password)
1445:       @header['proxy-authorization'] = [basic_encode(account, password)]
1446:     end

Returns an Array of Range objects which represents Range: header field, or nil if there is no such header.

[Source]

      # File lib/net/http.rb, line 1276
1276:     def range
1277:       return nil unless @header['range']
1278:       self['Range'].split(/,/).map {|spec|
1279:         m = /bytes\s*=\s*(\d+)?\s*-\s*(\d+)?/i.match(spec) or
1280:                 raise HTTPHeaderSyntaxError, "wrong Range: #{spec}"
1281:         d1 = m[1].to_i
1282:         d2 = m[2].to_i
1283:         if    m[1] and m[2] then  d1..d2
1284:         elsif m[1]          then  d1..-1
1285:         elsif          m[2] then -d2..-1
1286:         else
1287:           raise HTTPHeaderSyntaxError, 'range is not specified'
1288:         end
1289:       }
1290:     end
range=(r, e = nil)

Alias for set_range

The length of the range represented in Content-Range: header.

[Source]

      # File lib/net/http.rb, line 1367
1367:     def range_length
1368:       r = content_range() or return nil
1369:       r.end - r.begin
1370:     end

Set Content-Type: header field by type and params. type must be a String, params must be a Hash.

[Source]

      # File lib/net/http.rb, line 1414
1414:     def set_content_type(type, params = {})
1415:       @header['content-type'] = [type + params.map{|k,v|"; #{k}=#{v}"}.join('')]
1416:     end

Set header fields and a body from HTML form data. params should be a Hash containing HTML form data. Optional argument sep means data record separator.

This method also set Content-Type: header field to application/x-www-form-urlencoded.

[Source]

      # File lib/net/http.rb, line 1426
1426:     def set_form_data(params, sep = '&')
1427:       self.body = params.map {|k,v| "#{urlencode(k.to_s)}=#{urlencode(v.to_s)}" }.join(sep)
1428:       self.content_type = 'application/x-www-form-urlencoded'
1429:     end

Set Range: header from Range (arg r) or beginning index and length from it (arg idx&len).

  req.range = (0..1023)
  req.set_range 0, 1023

[Source]

      # File lib/net/http.rb, line 1298
1298:     def set_range(r, e = nil)
1299:       unless r
1300:         @header.delete 'range'
1301:         return r
1302:       end
1303:       r = (r...r+e) if e
1304:       case r
1305:       when Numeric
1306:         n = r.to_i
1307:         rangestr = (n > 0 ? "0-#{n-1}" : "-#{-n}")
1308:       when Range
1309:         first = r.first
1310:         last = r.last
1311:         last -= 1 if r.exclude_end?
1312:         if last == -1
1313:           rangestr = (first > 0 ? "#{first}-" : "-#{-first}")
1314:         else
1315:           raise HTTPHeaderSyntaxError, 'range.first is negative' if first < 0
1316:           raise HTTPHeaderSyntaxError, 'range.last is negative' if last < 0
1317:           raise HTTPHeaderSyntaxError, 'must be .first < .last' if first > last
1318:           rangestr = "#{first}-#{last}"
1319:         end
1320:       else
1321:         raise TypeError, 'Range/Integer is required'
1322:       end
1323:       @header['range'] = ["bytes=#{rangestr}"]
1324:       r
1325:     end

Returns a content type string such as "html". This method returns nil if Content-Type: header field does not exist or sub-type is not given (e.g. "Content-Type: text").

[Source]

      # File lib/net/http.rb, line 1392
1392:     def sub_type
1393:       return nil unless @header['content-type']
1394:       main, sub = *self['Content-Type'].split(';').first.to_s.split('/')
1395:       return nil unless sub
1396:       sub.strip
1397:     end

Returns a Hash consist of header names and values.

[Source]

      # File lib/net/http.rb, line 1256
1256:     def to_hash
1257:       @header.dup
1258:     end

Returns content type parameters as a Hash as like {"charset" => "iso-2022-jp"}.

[Source]

      # File lib/net/http.rb, line 1401
1401:     def type_params
1402:       result = {}
1403:       list = self['Content-Type'].to_s.split(';')
1404:       list.shift
1405:       list.each do |param|
1406:         k, v = *param.split('=', 2)
1407:         result[k.strip] = v.strip
1408:       end
1409:       result
1410:     end

Private Instance methods

[Source]

      # File lib/net/http.rb, line 1448
1448:     def basic_encode(account, password)
1449:       'Basic ' + ["#{account}:#{password}"].pack('m').delete("\r\n")
1450:     end

[Source]

      # File lib/net/http.rb, line 1269
1269:     def capitalize(name)
1270:       name.split(/-/).map {|s| s.capitalize }.join('-')
1271:     end

[Source]

      # File lib/net/http.rb, line 1433
1433:     def urlencode(str)
1434:       str.gsub(/[^a-zA-Z0-9_\.\-]/n) {|s| sprintf('%%%02x', s[0]) }
1435:     end

[Validate]