简体   繁体   中英

Post XML to an external API - Using cURL in Rails

I've been working in the Rails console with Rails 3.2 and I'm generating an XML file using Nokogiri. From here, I need to post to an external API to grab some data and return it within my app. Eventually this code will be a function of the controller, but for now I've been experimenting in the console.

I generated and XML file with Nokogiri and parameters I specified, and I stored the output using the following command:

File.open('results.xml', 'w') {|f| f.write(results)}

From here, I want to POST this file to the external API. The command I used saved it in the /public directory of my app. From here, I'm unsure of how to access it with cURL.

I tried putting it in a views directory and set up a route so I can GET the file, and I can at least access it. Here is what I tried in cURL (note that the Rails server was running at the time and the API path below is made up for example purposes):

curl -X POST -v --data-ascii http://localhost:3000/search/postresults.xml http://APIPATH/example.php

This one has been frustrating me for awhile, and when I try that I get an error saying:

SyntaxError: (irb):5: syntax error, unexpected tCONSTANT, expecting keyword_do or '{'  or '('
curl -X POST -v --data-ascii http://local...
        ^
(irb):5: syntax error, unexpected tUMINUS, expecting keyword_do or '{' or '('
curl -X POST -v --data-ascii http://localhost:...
             ^
(irb):5: syntax error, unexpected tLABEL, expecting keyword_do or '{' or '('
...l 
-X POST -v --data-ascii http://localhost:3000/search/postr...
...                               ^
(irb):5: unknown regexp options - lcalht

I've tried all of the standard troubleshooting (curl is installed - version 0.0.9, server is running, curl is in my Gemfile, etc), so any help is much appreciated. Thanks!

Your errors suggest that you typed the curl command and arguments directly into IRb. That's not how Ruby gems work. Furthermore, if you want to POST to an HTTP resource from Rails don't bother with cURL. Rails has built-in tools for this.

If you're going to be interacting with this API a lot, and if the API is fairly RESTy, then take a look at ActiveResource (tutorials abound on Google if the docs don't do it for you).

If you're not using a very RESTy API, or if this is a one-off API call, you can create an instance of ActiveResource::Connection directly, eg:

conn = ActiveResource::Connection.new 'http://example.com'

result = conn.post 'example.php', results

There's likely no need to write the Nokogiri document ( results ) to a file, just give it directly to ActiveResource::Connection#post .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM