ruby-on-rails - 使用 Rails 和 HTTParty 将 JSON 发布到 API

我希望我的 ruby​​ on rails 应用程序中的用户能够向我的外部工单管理系统 squishlist.com 提交工单。他们有一个 api 和说明如下。您需要进行身份验证并获取 token ,然后使用 token 提交票证。来自 squishlist。

# get the token

https://api.squishlist.com/auth/?cfg=testcorp&user_key=privatekey&api_key=TEST-KEY-12345
  => {"token": "authtoken",
      "expires": "2010-06-16 13:31:56"}

# and then the ticket with the token

https://api.squishlist.com/rest/?cfg=testcorp&token=authtoken&method=squish.issue.submit&prj=demo
  POST data: {'issue_type': 1, 'subject': 'Hello, world.', 4: 'Open', 5: 10}

出于测试目的,我创建了一个 Controller 、路由和 View (页面)进行测试。在我的 Controller 上,我有以下

require 'httparty'
require 'json'

class SubmitticketController < ApplicationController

    def submit_a_ticket

        @cfg = 'xxxsupport'
        @user_key = '4787fsdbbfbfsdbhbfad5aba91129a3f1ed1b743321f7b'
        @api_key = 'MrUser411'
        @project = 'excelm-manoke'
        @url_new_string = 'https://api.squishlist.com/auth/?cfg='+@cfg+'&user_key='+@user_key+'&api_key='+@api_key
        # https://api.squishlist.com/auth/?cfg=xxxsupport&user_key=4787fsdbbfbfsdbhbfad5aba91129a3f1ed1b743321f7b&api_key=MrUser411  - this is what is created by @url_new_string
        response =  HTTParty.get(@url_new_string.to_str)  #submit the string to get the token
        @parsed_and_a_hash = JSON.parse(response)
        @token = @parsed_and_a_hash["token"]


        #make a new string with the token

        @urlstring_to_post = 'https://api.squishlist.com/rest/?cfg='+@cfg+'&token='+@token+'&method=squish.issue.submit&prj='+@project

        #submit and get a result

        @result = HTTParty.post(@urlstring_to_post.to_str, :body => {:subject => 'This is the screen name', :issue_type => 'Application Problem', :status => 'Open', :priority => 'Normal', :description => 'This is the description for the problem'})

    end

end

然后我有一个页面可以查看 Controller 操作的结果,其中包含以下代码。

<p><%= @result %></p>

我知道它总体上是有效的,因为我在此过程中收到了回复。由于我在 squishlist 中定义的字段,我的 json 与示例不同。谁能帮我解决这个问题?

我想真正的问题是我无法真正看到 json 的样子,以及它是否接近匹配。我真的对json不太了解。我是否应该使用一些可能很容易的东西。我应该使用 ajax 来提交这个吗?任何帮助是极大的赞赏。我喜欢这里的社区。

最佳答案

我通过添加 .to_json 和一些标题信息解决了这个问题

@result = HTTParty.post(@urlstring_to_post.to_str, 
    :body => { :subject => 'This is the screen name', 
               :issue_type => 'Application Problem', 
               :status => 'Open', 
               :priority => 'Normal', 
               :description => 'This is the description for the problem'
             }.to_json,
    :headers => { 'Content-Type' => 'application/json' } )

https://stackoverflow.com/questions/7455744/

相关文章:

python - Python中的字符串到字典

python - 检查键是否存在并使用 Python 迭代 JSON 数组

json - 以友好的方式获取ffmpeg信息

json - JSON 值是否可以包含多行字符串

c# - 无法使用 Json 序列化 Web API 中的响应

ruby - 如何以正确的格式写入 JSON 文件

javascript - JavaScript 可以连接 MySQL 吗?

javascript - 将数据发布到 JsonP

python - 如何将 XML 字符串转换为字典?

json - 带 json 参数的 curl GET 请求