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 1158
1158:     def [](key)
1159:       a = @header[key.downcase] or return nil
1160:       a.join(', ')
1161:     end

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

[Source]

      # File lib/net/http.rb, line 1164
1164:     def []=(key, val)
1165:       unless val
1166:         @header.delete key.downcase
1167:         return val
1168:       end
1169:       @header[key.downcase] = [val]
1170:     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 1187
1187:     def add_field(key, val)
1188:       if @header.key?(key.downcase)
1189:         @header[key.downcase].push val
1190:       else
1191:         @header[key.downcase] = [val]
1192:       end
1193:     end

Set the Authorization: header for "Basic" authorization.

[Source]

      # File lib/net/http.rb, line 1443
1443:     def basic_auth(account, password)
1444:       @header['authorization'] = [basic_encode(account, password)]
1445:     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 1354
1354:     def chunked?
1355:       return false unless @header['transfer-encoding']
1356:       field = self['Transfer-Encoding']
1357:       (/(?:\A|[^\-\w])chunked(?![\-\w])/i =~ field) ? true : false
1358:     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 1335
1335:     def content_length
1336:       return nil unless key?('Content-Length')
1337:       len = self['Content-Length'].slice(/\d+/) or
1338:           raise HTTPHeaderSyntaxError, 'wrong Content-Length format'
1339:       len.to_i
1340:     end

[Source]

      # File lib/net/http.rb, line 1342
1342:     def content_length=(len)
1343:       unless len
1344:         @header.delete 'content-length'
1345:         return nil
1346:       end
1347:       @header['content-length'] = [len.to_i.to_s]
1348:     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 1363
1363:     def content_range
1364:       return nil unless @header['content-range']
1365:       m = %r<bytes\s+(\d+)-(\d+)/(\d+|\*)>i.match(self['Content-Range']) or
1366:           raise HTTPHeaderSyntaxError, 'wrong Content-Range format'
1367:       m[1].to_i .. m[2].to_i + 1
1368:     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 1378
1378:     def content_type
1379:       return nil unless main_type()
1380:       if sub_type()
1381:       then "#{main_type()}/#{sub_type()}"
1382:       else main_type()
1383:       end
1384:     end
content_type=(type, params = {})

Alias for set_content_type

Removes a header field.

[Source]

      # File lib/net/http.rb, line 1250
1250:     def delete(key)
1251:       @header.delete(key.downcase)
1252:     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 1265
1265:     def each_capitalized
1266:       @header.each do |k,v|
1267:         yield capitalize(k), v.join(', ')
1268:       end
1269:     end

Iterates for each capitalized header names.

[Source]

      # File lib/net/http.rb, line 1236
1236:     def each_capitalized_name(&block)   #:yield: +key+
1237:       @header.each_key do |k|
1238:         yield capitalize(k)
1239:       end
1240:     end

Iterates for each header names and values.

[Source]

      # File lib/net/http.rb, line 1220
1220:     def each_header   #:yield: +key+, +value+
1221:       @header.each do |k,va|
1222:         yield k, va.join(', ')
1223:       end
1224:     end
each_key()

Alias for each_name

Iterates for each header names.

[Source]

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

Iterates for each header values.

[Source]

      # File lib/net/http.rb, line 1243
1243:     def each_value   #:yield: +value+
1244:       @header.each_value do |va|
1245:         yield va.join(', ')
1246:       end
1247:     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 1214
1214:     def fetch(key, *args, &block)   #:yield: +key+
1215:       a = @header.fetch(key.downcase, *args, &block)
1216:       a.join(', ')
1217:     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 1206
1206:     def get_fields(key)
1207:       return nil unless @header[key.downcase]
1208:       @header[key.downcase].dup
1209:     end

[Source]

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

true if key header exists.

[Source]

      # File lib/net/http.rb, line 1255
1255:     def key?(key)
1256:       @header.key?(key.downcase)
1257:     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 1388
1388:     def main_type
1389:       return nil unless @header['content-type']
1390:       self['Content-Type'].split(';').first.to_s.split('/')[0].to_s.strip
1391:     end

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

[Source]

      # File lib/net/http.rb, line 1448
1448:     def proxy_basic_auth(account, password)
1449:       @header['proxy-authorization'] = [basic_encode(account, password)]
1450:     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 1280
1280:     def range
1281:       return nil unless @header['range']
1282:       self['Range'].split(/,/).map {|spec|
1283:         m = /bytes\s*=\s*(\d+)?\s*-\s*(\d+)?/i.match(spec) or
1284:                 raise HTTPHeaderSyntaxError, "wrong Range: #{spec}"
1285:         d1 = m[1].to_i
1286:         d2 = m[2].to_i
1287:         if    m[1] and m[2] then  d1..d2
1288:         elsif m[1]          then  d1..-1
1289:         elsif          m[2] then -d2..-1
1290:         else
1291:           raise HTTPHeaderSyntaxError, 'range is not specified'
1292:         end
1293:       }
1294:     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 1371
1371:     def range_length
1372:       r = content_range() or return nil
1373:       r.end - r.begin
1374:     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 1418
1418:     def set_content_type(type, params = {})
1419:       @header['content-type'] = [type + params.map{|k,v|"; #{k}=#{v}"}.join('')]
1420:     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 1430
1430:     def set_form_data(params, sep = '&')
1431:       self.body = params.map {|k,v| "#{urlencode(k.to_s)}=#{urlencode(v.to_s)}" }.join(sep)
1432:       self.content_type = 'application/x-www-form-urlencoded'
1433:     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 1302
1302:     def set_range(r, e = nil)
1303:       unless r
1304:         @header.delete 'range'
1305:         return r
1306:       end
1307:       r = (r...r+e) if e
1308:       case r
1309:       when Numeric
1310:         n = r.to_i
1311:         rangestr = (n > 0 ? "0-#{n-1}" : "-#{-n}")
1312:       when Range
1313:         first = r.first
1314:         last = r.last
1315:         last -= 1 if r.exclude_end?
1316:         if last == -1
1317:           rangestr = (first > 0 ? "#{first}-" : "-#{-first}")
1318:         else
1319:           raise HTTPHeaderSyntaxError, 'range.first is negative' if first < 0
1320:           raise HTTPHeaderSyntaxError, 'range.last is negative' if last < 0
1321:           raise HTTPHeaderSyntaxError, 'must be .first < .last' if first > last
1322:           rangestr = "#{first}-#{last}"
1323:         end
1324:       else
1325:         raise TypeError, 'Range/Integer is required'
1326:       end
1327:       @header['range'] = ["bytes=#{rangestr}"]
1328:       r
1329:     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 1396
1396:     def sub_type
1397:       return nil unless @header['content-type']
1398:       main, sub = *self['Content-Type'].split(';').first.to_s.split('/')
1399:       return nil unless sub
1400:       sub.strip
1401:     end

Returns a Hash consist of header names and values.

[Source]

      # File lib/net/http.rb, line 1260
1260:     def to_hash
1261:       @header.dup
1262:     end

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

[Source]

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

Private Instance methods

[Source]

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

[Source]

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

[Source]

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

[Validate]