【问题标题】:Ruby: How to access an api using HTTPartyRuby:如何使用 HTTParty 访问 api
【发布时间】:2015-02-12 23:22:23
【问题描述】:

我是 Ruby 和使用 HTTParty 的新手,并试图按照他们的github page 中的 HTTParty 示例执行基本 POST。当我运行下面的代码时出现错误:

require 'pp'
require 'HTTParty'
require 'pry'

class Partay
    include HTTParty
    base_uri "http://<myapidomain>/search/semanticsearch/query/"
end

options= {
    query: {
        version: "0.4",
        query: "lawyer"
    }}

response = Partay.post(options)

puts response

我得到的错误是:

rbenv/versions/2.2.0/lib/ruby/2.2.0/uri/common.rb:715:in `URI': bad argument (expected URI object or URI string) (ArgumentError)
from ~/.ruby/2.2.0/gems/httparty-0.13.3/lib/httparty/request.rb:47:in `path='
from ~/.ruby/2.2.0/gems/httparty-0.13.3/lib/httparty/request.rb:34:in `initialize'
from ~/.ruby/2.2.0/gems/httparty-0.13.3/lib/HTTParty.rb:539:in `new'
from ~/.ruby/2.2.0/gems/httparty-0.13.3/lib/HTTParty.rb:539:in `perform_request'
from ~/.ruby/2.2.0/gems/httparty-0.13.3/lib/HTTParty.rb:491:in `post'
from json-to-csv.rb:16:in `<main>'

我正在寻找的是调用一个接收 JSON 的帖子,其方式与调用此 URL 的工作方式相同:

http://somedomain.com/search/semanticsearch/query/?version=0.4&query=lawyer

【问题讨论】:

  • 考虑使用 Unirest,它更简单且可读性更强。 www.unirest.io
  • 谢谢,这真的很有用!

标签: ruby http-post httparty


【解决方案1】:

使用建议的 gem 记录解决方案 - unirest:

require 'unirest'

url = "http://somedomain.com/search/semanticsearch/query"
response = Unirest.post url, 
                        headers:{ "Accept" => "application/json" }, 
                        parameters:{ :version => 0.4, :query => "lawyer" }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多