[英]How to post XML string to api Ruby Faraday
I tried to use Faraday library for Ruby to make the next post request for my API: Need to add API-Key = "xxxxxxxxxxxxxxx" to my header and sent XML inside body我尝试使用 Ruby 的 Faraday 库为我的 API 发出下一个 post 请求:需要将 API-Key = "xxxxxxxxxxxxxxx" 添加到我的标头并在正文中发送 XML
<time_entry>
<issue_id>1</issue_id>
<activity_id>9</activity_id>
<hours>1.0</hours>
<comments>Test</comments>
</time_entry>
That works perfect from the postman, but not work when I use the Faraday library.这对邮递员来说很完美,但当我使用法拉第图书馆时就不行了。
My code is:我的代码是:
require 'faraday'
xml = %&<time_entry><issue_id>1</issue_id><activity_id>9</activity_id><hours>1.0</hours><comments>automatic spent time</comments></time_entry>&
faraday = Faraday.new do |f|
f.request :multipart
f.request :url_encoded
f.adapter :net_http
f.headers["API-Key"]="xxxxxxxxxxxxxxx"
end
payload = {xml: xml}
faraday.post("http://localhost:3000/time_entries.xml", payload)
I got a next error:我遇到了下一个错误:
Completed 422 Unprocessable Entity in 8ms (Views: 0.4ms | ActiveRecord: 2.0ms)
Completed 406 Not Acceptable in 19ms (ActiveRecord: 2.9ms)
I use an alternative method - I sent JSON instead of XML, and use 'net/http'我使用另一种方法 - 我发送 JSON 而不是 XML,并使用“net/http”
require "json"
require 'net/http'
uri = URI("http://localhost:3000/time_entries.xml")
I create a new Post request, with JSON body, and that works well.我创建了一个带有 JSON 正文的新 Post 请求,效果很好。
req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
req["X-Redmine-API-Key"]="xxxxxxxxxxxxxxxxxxxx"
req.body = {time_entry: {issue_id:1, activity_id:9,hours: hours, comments: "Test" }}.to_json
res = Net::HTTP.start(uri.hostname, uri.port) do |http|
http.request(req)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.