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 1163
1163:     def [](key)
1164:       a = @header[key.downcase] or return nil
1165:       a.join(', ')
1166:     end

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

[Source]

      # File lib/net/http.rb, line 1169
1169:     def []=(key, val)
1170:       unless val
1171:         @header.delete key.downcase
1172:         return val
1173:       end
1174:       @header[key.downcase] = [val]
1175:     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 1192
1192:     def add_field(key, val)
1193:       if @header.key?(key.downcase)
1194:         @header[key.downcase].push val
1195:       else
1196:         @header[key.downcase] = [val]
1197:       end
1198:     end

Set the Authorization: header for "Basic" authorization.

[Source]

      # File lib/net/http.rb, line 1448
1448:     def basic_auth(account, password)
1449:       @header['authorization'] = [basic_encode(account, password)]
1450:     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 1359
1359:     def chunked?
1360:       return false unless @header['transfer-encoding']
1361:       field = self['Transfer-Encoding']
1362:       (/(?:\A|[^\-\w])chunked(?![\-\w])/i =~ field) ? true : false
1363:     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 1340
1340:     def content_length
1341:       return nil unless key?('Content-Length')
1342:       len = self['Content-Length'].slice(/\d+/) or
1343:           raise HTTPHeaderSyntaxError, 'wrong Content-Length format'
1344:       len.to_i
1345:     end

[Source]

      # File lib/net/http.rb, line 1347
1347:     def content_length=(len)
1348:       unless len
1349:         @header.delete 'content-length'
1350:         return nil
1351:       end
1352:       @header['content-length'] = [len.to_i.to_s]
1353:     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 1368
1368:     def content_range
1369:       return nil unless @header['content-range']
1370:       m = %r<bytes\s+(\d+)-(\d+)/(\d+|\*)>i.match(self['Content-Range']) or
1371:           raise HTTPHeaderSyntaxError, 'wrong Content-Range format'
1372:       m[1].to_i .. m[2].to_i + 1
1373:     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 1383
1383:     def content_type
1384:       return nil unless main_type()
1385:       if sub_type()
1386:       then "#{main_type()}/#{sub_type()}"
1387:       else main_type()
1388:       end
1389:     end
content_type=(type, params = {})

Alias for set_content_type

Removes a header field.

[Source]

      # File lib/net/http.rb, line 1255
1255:     def delete(key)
1256:       @header.delete(key.downcase)
1257:     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 1270
1270:     def each_capitalized
1271:       @header.each do |k,v|
1272:         yield capitalize(k), v.join(', ')
1273:       end
1274:     end

Iterates for each capitalized header names.

[Source]

      # File lib/net/http.rb, line 1241
1241:     def each_capitalized_name(&block)   #:yield: +key+
1242:       @header.each_key do |k|
1243:         yield capitalize(k)
1244:       end
1245:     end

Iterates for each header names and values.

[Source]

      # File lib/net/http.rb, line 1225
1225:     def each_header   #:yield: +key+, +value+
1226:       @header.each do |k,va|
1227:         yield k, va.join(', ')
1228:       end
1229:     end
each_key()

Alias for each_name

Iterates for each header names.

[Source]

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

Iterates for each header values.

[Source]

      # File lib/net/http.rb, line 1248
1248:     def each_value   #:yield: +value+
1249:       @header.each_value do |va|
1250:         yield va.join(', ')
1251:       end
1252:     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 1219
1219:     def fetch(key, *args, &block)   #:yield: +key+
1220:       a = @header.fetch(key.downcase, *args, &block)
1221:       a.join(', ')
1222:     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 1211
1211:     def get_fields(key)
1212:       return nil unless @header[key.downcase]
1213:       @header[key.downcase].dup
1214:     end

[Source]

      # File lib/net/http.rb, line 1146
1146:     def initialize_http_header(initheader)
1147:       @header = {}
1148:       return unless initheader
1149:       initheader.each do |key, value|
1150:         warn "net/http: warning: duplicated HTTP header: #{key}" if key?(key) and $VERBOSE
1151:         @header[key.downcase] = [value.strip]
1152:       end
1153:     end

true if key header exists.

[Source]

      # File lib/net/http.rb, line 1260
1260:     def key?(key)
1261:       @header.key?(key.downcase)
1262:     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 1393
1393:     def main_type
1394:       return nil unless @header['content-type']
1395:       self['Content-Type'].split(';').first.to_s.split('/')[0].to_s.strip
1396:     end

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

[Source]

      # File lib/net/http.rb, line 1453
1453:     def proxy_basic_auth(account, password)
1454:       @header['proxy-authorization'] = [basic_encode(account, password)]
1455:     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 1285
1285:     def range
1286:       return nil unless @header['range']
1287:       self['Range'].split(/,/).map {|spec|
1288:         m = /bytes\s*=\s*(\d+)?\s*-\s*(\d+)?/i.match(spec) or
1289:                 raise HTTPHeaderSyntaxError, "wrong Range: #{spec}"
1290:         d1 = m[1].to_i
1291:         d2 = m[2].to_i
1292:         if    m[1] and m[2] then  d1..d2
1293:         elsif m[1]          then  d1..-1
1294:         elsif          m[2] then -d2..-1
1295:         else
1296:           raise HTTPHeaderSyntaxError, 'range is not specified'
1297:         end
1298:       }
1299:     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 1376
1376:     def range_length
1377:       r = content_range() or return nil
1378:       r.end - r.begin
1379:     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 1423
1423:     def set_content_type(type, params = {})
1424:       @header['content-type'] = [type + params.map{|k,v|"; #{k}=#{v}"}.join('')]
1425:     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 1435
1435:     def set_form_data(params, sep = '&')
1436:       self.body = params.map {|k,v| "#{urlencode(k.to_s)}=#{urlencode(v.to_s)}" }.join(sep)
1437:       self.content_type = 'application/x-www-form-urlencoded'
1438:     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 1307
1307:     def set_range(r, e = nil)
1308:       unless r
1309:         @header.delete 'range'
1310:         return r
1311:       end
1312:       r = (r...r+e) if e
1313:       case r
1314:       when Numeric
1315:         n = r.to_i
1316:         rangestr = (n > 0 ? "0-#{n-1}" : "-#{-n}")
1317:       when Range
1318:         first = r.first
1319:         last = r.last
1320:         last -= 1 if r.exclude_end?
1321:         if last == -1
1322:           rangestr = (first > 0 ? "#{first}-" : "-#{-first}")
1323:         else
1324:           raise HTTPHeaderSyntaxError, 'range.first is negative' if first < 0
1325:           raise HTTPHeaderSyntaxError, 'range.last is negative' if last < 0
1326:           raise HTTPHeaderSyntaxError, 'must be .first < .last' if first > last
1327:           rangestr = "#{first}-#{last}"
1328:         end
1329:       else
1330:         raise TypeError, 'Range/Integer is required'
1331:       end
1332:       @header['range'] = ["bytes=#{rangestr}"]
1333:       r
1334:     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 1401
1401:     def sub_type
1402:       return nil unless @header['content-type']
1403:       main, sub = *self['Content-Type'].split(';').first.to_s.split('/')
1404:       return nil unless sub
1405:       sub.strip
1406:     end

Returns a Hash consist of header names and values.

[Source]

      # File lib/net/http.rb, line 1265
1265:     def to_hash
1266:       @header.dup
1267:     end

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

[Source]

      # File lib/net/http.rb, line 1410
1410:     def type_params
1411:       result = {}
1412:       list = self['Content-Type'].to_s.split(';')
1413:       list.shift
1414:       list.each do |param|
1415:         k, v = *param.split('=', 2)
1416:         result[k.strip] = v.strip
1417:       end
1418:       result
1419:     end

Private Instance methods

[Source]

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

[Source]

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

[Source]

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

[Validate]