2014-01-06 43 views
1

在我的Rails 4應用程序中,我正在處理只處理XML的API(是的,我希望它也是JSON)。Rails和XML請求

我必須做一個POST請求,並且XML字符串應該存儲在一個名爲xmlRequestString的參數中。

爲POST數據的XML結構爲:

<?xml version="1.0" encoding="UTF-8"?> 
<GetProperties> 
    <Auth> 
    <VendorId>UserID</ VendorId> 
    <VendorPassword>Password</VendorPassword> 
    </Auth> 
</GetProperties> 

因爲我從來沒有碰過XML之前可能有人告訴我我怎麼會真的發表了這一數據。

會是這樣的一個很好的方式去做它(從這裏借:Submitting POST data from the controller in rails to another website)?

require "uri" 
require "net/http" 

xml = 'xml string can go here' 
params = {'xmlRequestString' => xml} 
Net::HTTP.post_form(URI.parse('urlendpoint'),params) 
+0

你可以列出你已經先嚐試? – kddeisz

回答

2

您可以將其保存爲一個模板,並使用像常規html.erb模板中的實例變量。或者,您可以將其作爲模型中的一種方法。無論哪種方式,您都使用了一些需要一些動態數據的東西,並返回一個文本字符串,其中包含xml。然後,在您的控制器中,渲染模板或調用方法(如果將其放入模型中)並將其發佈到api。

#Template method of generating xml 
#app/views/properties/get_properties.rxml 
xml.instruct! :xml, :version=>"1.0", :encoding => "UTF-8" 
xml.GetProperties do 
    xml.Auth do 
    xml.VendorId do 
     <%= @user_id %> 
    end 
    xml.VendorPassword do 
     <%= @password %> 
    end 
    end 
end 

然後,控制器,調用API:

@user_id = "foo" 
@password = "bar" 
xml_string = render :template => "properties/get_properties.rxml", :layout => false 
http = Net::HTTP.new("www.the-api-website.com") 
response = http.post("/path/to/call/the/api", xml_string) 
+0

順便說一句,xml數據實際上只是一個文本字符串:沒有什麼不可思議的。您可以根據需要設置文本字符串。 –

+0

非常感謝這個 - 我現在會測試它,然後如果它能正常工作,就可以信任你。歡呼聲 – tommyd456

+0

我猜它從來沒有工作,因爲在這個時候沒有信用... @ tommyd456 –