我试图将数据从XML格式的数据库传递到API。我在控制器中编写了以下代码:
require 'active_support/builder' unless defined?(Builder)
require 'uri'
require 'net/http'
def gen_xml
xml = Builder::XmlMarkup.new
@customers = Customer.find(:all)
url = "http://.......................xml?";
request = Net::HTTP::Post.new(url)
request.add_field "Content-Type", "application/xml"
request.body = xml
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
response = http.request(request)
end
我已经用XML生成器创建了一个XML文件,但是我不能将这个XML数据传递给API。以上代码不会在日志中留下任何错误或任何正在执行的相应操作的痕迹。
嘿!终于想通了
我能够通过以下更改将数据传递给API:
1)最初,XML数据被
x = Builder::XmlMarkup.new(:target => out_string = "<?xml version='1.0' encoding='UTF-8'?>n", :indent =>1)
2)之后,使用这个'out_string'来传递xml数据。通过请求。Body = out_string;如下,
uri = URI.parse("http:............")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri)
request.body = out_string
response = http.request(request)