4

I'm using Net::HTTP in Ruby 1.9.2p290 to handle some, obviously, networking calls.

I now have a need to see the complete request that is sent to the server (as one long big String conforming to HTTP 1.0/1.1.

In other words, I want Net::HTTP to handle the heavy lifting of generating the HTTP standard-compliant request+body, but I want to send the string with a custom delivery mechanism.

Net::HTTPRequest doesn't seem to have any helpful methods here -- do I need to go lower down the stack and hijack something?

Does anyone know of a good library, maybe other than Net::HTTP, that could help?

EDIT: I'd also like to do the same going the other way (turning a string response into Net::HTTP::* -- although it seems I may be able to instantiate Net::HTTPResponse by myself?

makdad
  • 6,402
  • 3
  • 31
  • 56

1 Answers1

2

Request:

post = Net::HTTP::Post.new('http://google.com')
post.set_form_data :query => 'ruby http'
sio = StringIO.new
post.exec si, Net::HTTP::HTTPVersion, post.path
puts sio.string

Response:

si = StringIO.new("HTTP/1.1 200 OK\n")
bio = Net::BufferedIO.new(si)
Net::HTTPResponse.read_new(bio)
msorc
  • 907
  • 1
  • 7
  • 20
  • Seems very close. I'm using the Response code you've offered, but I'm getting - `NoMethodError: undefined method 'closed?' for nil:NilClass` when I call `read_new`. Particularly when I am parsing an HTTP response with no body. Also, when I have a string with no headers, `headers` is nil, instead of [] as I'd expect. – makdad May 22 '12 at 09:29
  • OH, and I forgot to say - THANKS! This is bringing me much closer. – makdad May 22 '12 at 09:29
  • Well, I figured out the second issue - it's `header`, not `headers` ;) – makdad May 22 '12 at 09:41