@@ -224,13 +224,32 @@ def initialize(httpv, code, msg) #:nodoc: internal use only
224
224
# Accept-Encoding header from the user.
225
225
attr_accessor :decode_content
226
226
227
- # The encoding to use for the response body. If Encoding, use that encoding.
228
- # If other true value, attempt to detect the appropriate encoding, and use
229
- # that.
227
+ # Returns the value set by body_encoding=, or +false+ if none;
228
+ # see #body_encoding=.
230
229
attr_reader :body_encoding
231
230
232
- # Set the encoding to use for the response body. If given a String, find
233
- # the related Encoding.
231
+ # Sets the encoding that should be used when reading the body:
232
+ #
233
+ # - If the given value is an Encoding object, that encoding will be used.
234
+ # - Otherwise if the value is a string, the value of
235
+ # {Encoding#find(value)}[https://docs.ruby-lang.org/en/master/Encoding.html#method-c-find]
236
+ # will be used.
237
+ # - Otherwise an encoding will be deduced from the body itself.
238
+ #
239
+ # Examples:
240
+ #
241
+ # http = Net::HTTP.new(hostname)
242
+ # req = Net::HTTP::Get.new('/')
243
+ #
244
+ # http.request(req) do |res|
245
+ # p res.body.encoding # => #<Encoding:ASCII-8BIT>
246
+ # end
247
+ #
248
+ # http.request(req) do |res|
249
+ # res.body_encoding = "UTF-8"
250
+ # p res.body.encoding # => #<Encoding:UTF-8>
251
+ # end
252
+ #
234
253
def body_encoding = ( value )
235
254
value = Encoding . find ( value ) if value . is_a? ( String )
236
255
@body_encoding = value
@@ -362,26 +381,26 @@ def read_body(dest = nil, &block)
362
381
@body
363
382
end
364
383
365
- # Returns the full entity body.
384
+ # Returns the string response body;
385
+ # note that repeated calls for the unmodified body return a cached string:
366
386
#
367
- # Calling this method a second or subsequent time will return the
368
- # string already read.
387
+ # path = '/todos/1'
388
+ # Net::HTTP.start(hostname) do |http|
389
+ # res = http.get(path)
390
+ # p res.body
391
+ # p http.head(path).body # No body.
392
+ # end
369
393
#
370
- # http.request_get('/index.html') {|res|
371
- # puts res.body
372
- # }
394
+ # Output:
373
395
#
374
- # http.request_get('/index.html') {|res|
375
- # p res.body.object_id # 538149362
376
- # p res.body.object_id # 538149362
377
- # }
396
+ # "{\n \"userId\": 1,\n \"id\": 1,\n \"title\": \"delectus aut autem\",\n \"completed\": false\n}"
397
+ # nil
378
398
#
379
399
def body
380
400
read_body ( )
381
401
end
382
402
383
- # Because it may be necessary to modify the body, Eg, decompression
384
- # this method facilitates that.
403
+ # Sets the body of the response to the given value.
385
404
def body = ( value )
386
405
@body = value
387
406
end
0 commit comments