【问题标题】:How to post XML string to api Ruby Faraday如何将 XML 字符串发布到 api Ruby Faraday
【发布时间】:2019-12-05 13:38:47
【问题描述】:

我尝试使用 Faraday Ruby 库为我的 API 发出下一个帖子请求: 需要在我的标头中添加 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>

这对邮递员来说很完美,但当我使用法拉第图书馆时就不行了。

我的代码是:

 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)

我收到下一个错误:

Completed 422 Unprocessable Entity in 8ms (Views: 0.4ms | ActiveRecord: 2.0ms)
Completed 406 Not Acceptable in 19ms (ActiveRecord: 2.9ms)

【问题讨论】:

    标签: ruby-on-rails ruby redmine-api


    【解决方案1】:

    我使用另一种方法 - 我发送 JSON 而不是 XML,并使用 'net/http'

      require "json"
      require 'net/http'
      uri = URI("http://localhost:3000/time_entries.xml")
    

    我创建了一个带有 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-02
      • 2017-09-10
      • 2015-10-21
      • 1970-01-01
      • 2016-03-25
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      相关资源
      最近更新 更多