在Ruby中与Yahoo Placemaker进行交互

时间:2012-02-19 19:18:52

标签: ruby api yahoo-api net-http

我正在尝试使用net/http与Yahoo Placemaker API进行交互,但我似乎无法让它工作。以下是我到目前为止的情况:

host = 'wherein.yahooapis.com'
payload = {
    'documentContent' => 'Columbus Ohio',
    'appid' => APP_ID,
    'outputType' => 'json',
    'documentType' => 'text/plain'
}.to_json

req = Net::HTTP::Post.new('/v1/document', initheader = { 'Content-Type' =>'application/json'})
req.body = payload
response = Net::HTTP.new(host).start {|http| http.request(req) }
puts "Response #{response.code} #{response.message}: #{response.body}"

这给了我以下错误:

Errno::ECONNREFUSED: Connection refused - connect(2)
    from /Users/Kyle/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/net/http.rb:762:in `initialize'
    from /Users/Kyle/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/net/http.rb:762:in `open'
    from /Users/Kyle/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/net/http.rb:762:in `block in connect'
    from /Users/Kyle/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/timeout.rb:54:in `timeout'
    from /Users/Kyle/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/timeout.rb:99:in `timeout'
    from /Users/Kyle/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/net/http.rb:762:in `connect'
    from /Users/Kyle/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/net/http.rb:755:in `do_start'
    from /Users/Kyle/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/net/http.rb:744:in `start'
    from /Users/Kyle/Desktop/skateparks-web/lib/yahoo/placemaker.rb:21:in `extract'
    from (irb):3
    from /Users/Kyle/.rvm/rubies/ruby-1.9.3-p0/bin/irb:16:in `<main>'

修复@host错字后,我现在得到:

Response 400 Bad Request:
<?xml version="1.0" encoding="UTF-8" ?>
<yahoo:error xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" xmlns:cle="http://wherein.yahooapis.com/v1/schema.rng" xmlns:xml="http://www.w3.org/XML/1998/namespace" xml:lang="en"><yahoo:description><![CDATA[Please provide a document URL or content.]]></yahoo:description>
<yahoo:detail><code>-9999</code>
<cause>input</cause>
</yahoo:detail></yahoo:error>

2 个答案:

答案 0 :(得分:1)

您正在向他们发送json,他们似乎在帖子正文中寻找常规查询字符串。此外,您应该使用httparty来使用Web服务,除非您有充分的理由不这样做:

require 'httparty'

class Yahoo
    include HTTParty
    base_uri 'http://wherein.yahooapis.com/'
end

json = Yahoo.post '/v1/document', :body => {:documentContent => 'Columbus Ohio', :appid => APP_ID, :outputType => 'json', :documentType => 'text/plain'}

答案 1 :(得分:0)

可能只是一个错字? @host应该是host对吗?