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

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

[Source]

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

Set the Authorization: header for "Basic" authorization.

[Source]

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

[Source]

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

Alias for set_content_type

Removes a header field.

[Source]

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

Iterates for each capitalized header names.

[Source]

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

Iterates for each header names and values.

[Source]

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

Alias for each_name

Iterates for each header names.

[Source]

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

Iterates for each header values.

[Source]

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

[Source]

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

true if key header exists.

[Source]

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

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

[Source]

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

Returns a Hash consist of header names and values.

[Source]

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

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

[Source]

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

Private Instance methods

[Source]

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

[Source]

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

[Source]

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

[Validate]