1
0
Fork 0
mirror of https://github.com/rest-client/rest-client.git synced 2022-11-09 13:49:40 -05:00

patched RequestClient.post to treat a payload in the form of a hash as a batch of form-encoded data, including adding the relevant header

This commit is contained in:
Greg Borenstein 2008-03-27 15:54:03 -07:00
parent 7e162d784b
commit 8bbe5b26f4
2 changed files with 34 additions and 1 deletions

View file

@ -42,8 +42,8 @@ module RestClient
def initialize(args)
@method = args[:method] or raise ArgumentError, "must pass :method"
@url = args[:url] or raise ArgumentError, "must pass :url"
@payload = args[:payload]
@headers = args[:headers] || {}
@payload = process_payload(args[:payload])
@user = args[:user]
@password = args[:password]
end
@ -87,6 +87,15 @@ module RestClient
# Authorization is required to access the resource specified.
class Unauthorized < Exception; end
def process_payload(p=nil)
if p && p.is_a?( Hash ) && method == :post
@headers[:content_type] = 'application/x-www-form-urlencoded'
p.keys.collect{|k| "#{k}=#{URI.escape(p[k])}"}.join("&")
else
p
end
end
def transmit(uri, req, payload)
setup_credentials(req)

View file

@ -23,6 +23,28 @@ describe RestClient do
end
end
context "RestClient with a hash of form data as a payload" do
before do
@request = RestClient::Request.new(:method => :post, :url => 'http://some/resource', :payload => {:email => "my@email.com", :password =>"secrets"})
@uri = mock("uri")
@uri.stub!(:request_uri).and_return('/resource')
@uri.stub!(:host).and_return('some')
@uri.stub!(:port).and_return(80)
Net::HTTP::Post.stub!(:new).and_return(@net = mock('Net::HTTP::Post'))
@request.stub!(:transmit)
end
it "should set the payload to be the hash processed into URI params" do
@request.should_receive(:transmit).with(URI.parse('http://some/resource'), @net, "email=my@email.com&password=secrets")
@request.execute_inner
end
it "should add the 'application/x-www-form-urlencoded' content_type header" do
@request.should_receive(:make_headers).with({:content_type => 'application/x-www-form-urlencoded'})
@request.execute_inner
end
end
context RestClient::Request do
before do
@request = RestClient::Request.new(:method => :put, :url => 'http://some/resource', :payload => 'payload')
@ -139,3 +161,5 @@ describe RestClient do
end
end
end