سؤال

I am attempting to learn Ruby/Faraday. I need to POST XML to a RESTful web service and am confused on how to do this.

I have a string containing the XML as follows:

require "faraday"
require "faraday_middleware"
mystring = %&<xml><auth><user userid='username' pwd='password'/></auth></xml>&

How do I post the XML to a URL and receive the result? I am trying to do something like:

conn = Faraday.new(:url=>'http://url')
conn.post '/logon' {mystring}

I get the message:

SyntaxError: (irb):11: syntax error, unexpected '{', expecting $end
conn.post '/logon' {mystring}

Edit 1 I have gotten the POST request to work. My code is provided below.

require "faraday"
require "faraday_middleware"

myString = %&<xml><auth><user userid='username' pwd='password'/></auth></xml>&
myUrl = %&url&

conn = Faraday.new(:url => myUrl) do |builder|
  builder.response :logger #logging stuff
  builder.use Faraday::Adapter::NetHttp #default adapter for Net::HTTP
end

res = conn.post do |request|
  request.url myUrl
  request.body = myString
end

puts res.body
هل كانت مفيدة؟

المحلول

According to the documentation:

conn = Faraday.new(:url=>'http://url')
conn.post '/logon', mystring

There are two errors in your code. The first one is that you are missing a comma between the URL and the variable causing { mystring } to be interpreted as a block.

The second error is that mystring already holds a string and the following code does not make sense in Ruby:

 { "string" }

Thus conn.post '/logon', mystring is wrong. So the final result is:

conn = Faraday.new(:url=>'http://url')
conn.post '/logon', mystring

or:

conn = Faraday.new(:url=>'http://url')
conn.post '/logon', { :key => mystring }

if you want to submit a key/value POST body. But this is not your case, because you are already posting an XML body.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top