3

I'm having trouble translating this CURL request into Ruby using RestClient:

system("curl --digest -u #{@user}:#{@pass} '#{@endpoint}/#{id}' --form image_file=@'#{path}' -X PUT")

I keep getting 400 Bad Request errors. As far as I can tell, the request does get properly authenticated, but hangs up from the file upload part. Here are my best attempts, all of which get me those 400 errors:

resource = RestClient::Resource.new "#{@endpoint}/#{id}", @user, @pass
#attempt 1
resource.put :image_file => File.new(path, 'rb'), :content_type => 'image/jpg'
#attempt 2
resource.put File.read(path), :content_type => 'image/jpg'
#attempt 3
resource.put File.open(path) {|f| f.read}, :content_type => 'image/jpg'
user94154
  • 16,176
  • 20
  • 77
  • 116
  • You should not be passing content_typa as image/jpg because you are submitting an encoded form. I would simply try the put like so `resource.put :image_file => File.new(path, 'rb')` Also see this stackoverflow post http://stackoverflow.com/questions/184178/ruby-how-to-post-a-file-via-http-as-multipart-form-data – Moiz Raja Nov 11 '11 at 17:45
  • removing the content_type doesn't change anything. I'm thinking this might have to do with the path provided. The path given is an absolute path which works fine in CURL. How could I make File.read handle an absolute path? – user94154 Nov 11 '11 at 22:23

3 Answers3

2

in the curl request you are sending multipart form-data via the PUT-request, so accordingly, you need to do the same in RestClient:

resource = RestClient::Resource.new "#{@endpoint}/#{id}", @user, @pass
resource.put :image_file => File.new(path, 'rb'), :content_type => 'multipart/form-data', :multipart => true
robustus
  • 3,626
  • 1
  • 26
  • 24
1

Robustus is right, you could also use a RestClient::Payload::Multipart.

However I have seen that you're asking this for your Moodstocks gem (https://github.com/adelevie/moodstocks). You will have another problem which is that (AFAIK) RestClient cannot handle HTTP Digest authentication.

You will need to use another library such as HTTParty for that. You can still use RestClient::Payload::Multipart to generate the payload as demonstrated here: https://github.com/Moodstocks/moodstocks-api/blob/master/moodstocks-api/msapi.rb

You could also use one of the cURL bindings or Rufus::Verbs if you want.

catwell
  • 6,770
  • 1
  • 23
  • 21
0

You need to examine the requests to determine where they differ. You can try capturing your traffic with wireshark or proxying the requests through fiddler or charles.

pguardiario
  • 53,827
  • 19
  • 119
  • 159