makdad
makdad

Reputation: 6450

Can I reference a complete Ruby Net::HTTP request as a string before sending?

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?

Upvotes: 4

Views: 868

Answers (1)

msorc
msorc

Reputation: 917

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)

Upvotes: 2

Related Questions