我正在使用第三方API(Spreadshirt的API),为了执行一个篮子创建,我需要通过POST请求发送一个xml。我试图用可用的Net :: HTTP函数做这个,这就是我这样做的方式
def get_session
@time = Time.now.to_i * 1000 #get the current time as integer
@sha1 = Digest::SHA1.hexdigest("POST http://api.spreadshirt.com/api/v1/baskets #{@time} #{ENV['SPREADSHIRT_SECRET_KEY']}") #encrypt the signature
@http = Net::HTTP.new("http://api.spreadshirt.com")
@path = "/api/v1/baskets?apiKey=#{ENV['SPREADSHIRT_API_KEY']}&sig=#{@sha1}&time=#{@time}"
@payload = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>
<basket xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns=\"http://api.spreadshirt.net\">
</basket>"
@response = @http.request_post(@path, @payload)
end
时间=&gt; “时间戳为签名中使用的毫秒数,例如1240575575156。”
sig =&gt;“签名为SHA-1为字符串的十六进制'METHOD URL_WITHOUT_QUERY TIMESTAMP SECRET',例如'POST http://localhost:8080/api/v1/users/42/productPriceCalculator 1240575575156 987654321'。(在实时系统中使用您自己的秘密)。”
apiKey =&gt; “请求的API密钥,例如123456789(在实时系统上使用您自己的密钥)。”
有关规范的更多信息,请访问以下链接: http://api.spreadshirt.net/api/v1/metaData/api.html#N218D1 http://wiki.developer.spreadshirt.net/display/API/Basket+Resources
我只是想知道我是否正确使用了Net :: HTTP函数,或者假设我使用了正确的密钥和api密钥。
供应商提供了PHP示例代码,可在此处找到 http://spreadshirtapps.svn.sourceforge.net/viewvc/spreadshirtapps/php/sod/ 文件sprd / CheckoutController.php是一个类似于我想要做的事情。
答案 0 :(得分:2)
许多Web服务要求您告诉他们您通过Content-Type标头发送XML。对于Net :: HTTP,请尝试以下方法:
url = "http://.../api/v1/baskets?..."
payload = "..."
require 'net/http'
request = Net::HTTP::Post.new(url)
request.add_field "Content-Type", "application/xml"
request.body = payload
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
response = http.request(request)
答案 1 :(得分:0)
资源:我使用Net::HTTP Cheat Sheet
答案:
您的代码看起来不错。虽然我不确定你为什么要使用这么多实例变量而不是本地变量。
你收到什么错误?
<强>加了:强>
400状态代码是“错误请求”,但更重要的是,它可能来自服务器的应用程序,而不是HTTP服务器本身(Apache等)。
建议:
运行他们给你的php示例程序。使确定它适用于您尝试从Ruby / Rails执行的功能。
然后使用Wireshark或其他以太网peeker来查看完全从示例客户端发送到服务器以及从客户端发送到服务器的内容。你的任务是让你的Ruby / Rails做与样本sw完全相同的事情。
按照Harold L的建议设置内容类型是一个好主意。
但是您还需要确保您的代码完全(直到位)模拟其工作示例代码在网络上执行的操作。文档与实现不太匹配是很常见的,特别是在像Spreadshirt这样的早期api版本中。
我的猜测是,他们应该很高兴你在他们的api工作。他们有动力为您提供帮助。
祝你好运。