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 1151
1151:     def [](key)
1152:       a = @header[key.downcase] or return nil
1153:       a.join(', ')
1154:     end

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

[Source]

      # File lib/net/http.rb, line 1157
1157:     def []=(key, val)
1158:       unless val
1159:         @header.delete key.downcase
1160:         return val
1161:       end
1162:       @header[key.downcase] = [val]
1163:     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 1180
1180:     def add_field(key, val)
1181:       if @header.key?(key.downcase)
1182:         @header[key.downcase].push val
1183:       else
1184:         @header[key.downcase] = [val]
1185:       end
1186:     end

Set the Authorization: header for "Basic" authorization.

[Source]

      # File lib/net/http.rb, line 1436
1436:     def basic_auth(account, password)
1437:       @header['authorization'] = [basic_encode(account, password)]
1438:     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 1347
1347:     def chunked?
1348:       return false unless @header['transfer-encoding']
1349:       field = self['Transfer-Encoding']
1350:       (/(?:\A|[^\-\w])chunked(?![\-\w])/i =~ field) ? true : false
1351:     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 1328
1328:     def content_length
1329:       return nil unless key?('Content-Length')
1330:       len = self['Content-Length'].slice(/\d+/) or
1331:           raise HTTPHeaderSyntaxError, 'wrong Content-Length format'
1332:       len.to_i
1333:     end

[Source]

      # File lib/net/http.rb, line 1335
1335:     def content_length=(len)
1336:       unless len
1337:         @header.delete 'content-length'
1338:         return nil
1339:       end
1340:       @header['content-length'] = [len.to_i.to_s]
1341:     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 1356
1356:     def content_range
1357:       return nil unless @header['content-range']
1358:       m = %r<bytes\s+(\d+)-(\d+)/(\d+|\*)>i.match(self['Content-Range']) or
1359:           raise HTTPHeaderSyntaxError, 'wrong Content-Range format'
1360:       m[1].to_i .. m[2].to_i + 1
1361:     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 1371
1371:     def content_type
1372:       return nil unless main_type()
1373:       if sub_type()
1374:       then "#{main_type()}/#{sub_type()}"
1375:       else main_type()
1376:       end
1377:     end
content_type=(type, params = {})

Alias for set_content_type

Removes a header field.

[Source]

      # File lib/net/http.rb, line 1243
1243:     def delete(key)
1244:       @header.delete(key.downcase)
1245:     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 1258
1258:     def each_capitalized
1259:       @header.each do |k,v|
1260:         yield capitalize(k), v.join(', ')
1261:       end
1262:     end

Iterates for each capitalized header names.

[Source]

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

Iterates for each header names and values.

[Source]

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

Alias for each_name

Iterates for each header names.

[Source]

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

Iterates for each header values.

[Source]

      # File lib/net/http.rb, line 1236
1236:     def each_value   #:yield: +value+
1237:       @header.each_value do |va|
1238:         yield va.join(', ')
1239:       end
1240:     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 1207
1207:     def fetch(key, *args, &block)   #:yield: +key+
1208:       a = @header.fetch(key.downcase, *args, &block)
1209:       a.join(', ')
1210:     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 1199
1199:     def get_fields(key)
1200:       return nil unless @header[key.downcase]
1201:       @header[key.downcase].dup
1202:     end

[Source]

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

true if key header exists.

[Source]

      # File lib/net/http.rb, line 1248
1248:     def key?(key)
1249:       @header.key?(key.downcase)
1250:     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 1381
1381:     def main_type
1382:       return nil unless @header['content-type']
1383:       self['Content-Type'].split(';').first.to_s.split('/')[0].to_s.strip
1384:     end

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

[Source]

      # File lib/net/http.rb, line 1441
1441:     def proxy_basic_auth(account, password)
1442:       @header['proxy-authorization'] = [basic_encode(account, password)]
1443:     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 1273
1273:     def range
1274:       return nil unless @header['range']
1275:       self['Range'].split(/,/).map {|spec|
1276:         m = /bytes\s*=\s*(\d+)?\s*-\s*(\d+)?/i.match(spec) or
1277:                 raise HTTPHeaderSyntaxError, "wrong Range: #{spec}"
1278:         d1 = m[1].to_i
1279:         d2 = m[2].to_i
1280:         if    m[1] and m[2] then  d1..d2
1281:         elsif m[1]          then  d1..-1
1282:         elsif          m[2] then -d2..-1
1283:         else
1284:           raise HTTPHeaderSyntaxError, 'range is not specified'
1285:         end
1286:       }
1287:     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 1364
1364:     def range_length
1365:       r = content_range() or return nil
1366:       r.end - r.begin
1367:     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 1411
1411:     def set_content_type(type, params = {})
1412:       @header['content-type'] = [type + params.map{|k,v|"; #{k}=#{v}"}.join('')]
1413:     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 1423
1423:     def set_form_data(params, sep = '&')
1424:       self.body = params.map {|k,v| "#{urlencode(k.to_s)}=#{urlencode(v.to_s)}" }.join(sep)
1425:       self.content_type = 'application/x-www-form-urlencoded'
1426:     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 1295
1295:     def set_range(r, e = nil)
1296:       unless r
1297:         @header.delete 'range'
1298:         return r
1299:       end
1300:       r = (r...r+e) if e
1301:       case r
1302:       when Numeric
1303:         n = r.to_i
1304:         rangestr = (n > 0 ? "0-#{n-1}" : "-#{-n}")
1305:       when Range
1306:         first = r.first
1307:         last = r.last
1308:         last -= 1 if r.exclude_end?
1309:         if last == -1
1310:           rangestr = (first > 0 ? "#{first}-" : "-#{-first}")
1311:         else
1312:           raise HTTPHeaderSyntaxError, 'range.first is negative' if first < 0
1313:           raise HTTPHeaderSyntaxError, 'range.last is negative' if last < 0
1314:           raise HTTPHeaderSyntaxError, 'must be .first < .last' if first > last
1315:           rangestr = "#{first}-#{last}"
1316:         end
1317:       else
1318:         raise TypeError, 'Range/Integer is required'
1319:       end
1320:       @header['range'] = ["bytes=#{rangestr}"]
1321:       r
1322:     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 1389
1389:     def sub_type
1390:       return nil unless @header['content-type']
1391:       main, sub = *self['Content-Type'].split(';').first.to_s.split('/')
1392:       return nil unless sub
1393:       sub.strip
1394:     end

Returns a Hash consist of header names and values.

[Source]

      # File lib/net/http.rb, line 1253
1253:     def to_hash
1254:       @header.dup
1255:     end

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

[Source]

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

Private Instance methods

[Source]

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

[Source]

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

[Source]

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

[Validate]