Permalink
Browse files

Do not read IO till EOF when the size is given

HTTPClient checks if the given IO responds to :size and set
"Content-Length" header if the size is given.  But it read too much till
EOF.  Should read just as the specified size.

To make the logic simple, now HTTPClient doesn't try to calculate the
whole size of request body for Content-Length if the request body is a
multipart and contains an IO as a parameter.

Fixes #117.
  • Loading branch information...
1 parent 57d9993 commit 1270672152eefea536cf7723fcd78974d2b4057e @nahi committed Oct 10, 2012
Showing with 21 additions and 12 deletions.
  1. +11 −12 lib/httpclient/http.rb
  2. +10 −0 test/test_httpclient.rb
View
@@ -562,12 +562,21 @@ def reset_pos(io)
end
def dump_file(io, dev)
+ return dump_file_length(io, @size, dev) if @size
buf = ''
while !io.read(@chunk_size, buf).nil?
dev << buf
end
end
+ def dump_file_length(io, size, dev)
+ buf = ''
+ while size > 0 && !(read = io.read(size > @chunk_size ? @chunk_size : size, buf)).nil?
+ dev << buf
+ size -= read.bytesize
+ end
+ end
+
def dump_chunks(io, dev)
buf = ''
while !io.read(@chunk_size, buf).nil?
@@ -600,18 +609,8 @@ def add(part)
if Message.file?(part)
@as_stream = true
@body << part
- if part.respond_to?(:lstat)
- @size += part.lstat.size
- elsif part.respond_to?(:size)
- if sz = part.size
- @size += sz
- else
- @size = nil
- end
- else
- # use chunked upload
- @size = nil
- end
+ # use chunked upload
+ @size = nil
elsif @body[-1].is_a?(String)
@body[-1] += part.to_s
@size += part.to_s.bytesize if @size
View
@@ -794,6 +794,16 @@ def myio.size
assert_match(/\r\nTransfer-Encoding: chunked\r\n/m, str.string)
end
+ def test_post_with_io_size_mismatch
+ myio = StringIO.new("45")
+ def myio.size
+ 1
+ end
+ @client.debug_dev = str = StringIO.new
+ res = @client.post(serverurl + 'servlet', myio)
+ assert_match(/\r\n4\n/, str.string, 'should send "4" not "45"')
+ end
+
def test_post_async
param = {'1'=>'2', '3'=>'4'}
conn = @client.post_async(serverurl + 'servlet', param)

0 comments on commit 1270672

Please sign in to comment.