Ruby-on-rails 使用 Rails 和 HTTParty 将 JSON POST 到 API

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7455744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:59:09  来源:igfitidea点击:

POST JSON to API using Rails and HTTParty

ruby-on-railsjsonapihttparty

提问by Homer Jon

I would like for a user within my ruby on rails app to be able to submit a ticket to my external ticket management system, squishlist.com. They have an api and instructions as follows. You need to authenticate and get a token and then submit the ticket with the token. From squishlist.

我希望我的 ruby​​ on rails 应用程序中的用户能够向我的外部票务管理系统 squishlist.com 提交票证。他们有一个 api 和说明如下。您需要进行身份验证并获取令牌,然后使用令牌提交票证。来自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}

For testing purposes, I created a controller, route and view (page) for testing. On my controller I have the following

出于测试目的,我创建了一个控制器、路由和视图(页面)进行测试。在我的控制器上,我有以下内容

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

And then I have a page that I go to to see the result of the controllers actions and it has the following code.

然后我有一个页面可以查看控制器操作的结果,它包含以下代码。

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

I know that it is working in general because of responses I have received along the way. My json is different from the example because of fields I have defined in squishlist. Can anyone help me out on this issue?

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

I guess the real problem is that I can't really see what the json looks like and if it is even close to match. I really don't know much about json. Should I be using something that might be easy. Should I be using ajax to submit this. Any help is greatly appreciated. I love the community here.

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

回答by Homer Jon

I solved this by adding .to_jsonand some heading information

我通过添加.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' } )

回答by Brian McNabb

The :query_string_normalizeroption is also available, which will override the default normalizer HashConversions.to_params(query)

:query_string_normalizer选项也可用,它将覆盖默认的规范化器HashConversions.to_params(query)

query_string_normalizer: ->(query){query.to_json}