1

我正在尝试对大致如下所示的外部服务执行 Rails POST 请求:

def self.send_post_request(domain, data)
 uri = URI.parse(domain)
 http = Net::HTTP.new(uri.host, uri.port)
 request = Net::HTTP::Post.new(uri.request_uri)
 request.set_form_data(data)
 http.use_ssl = true if domain =~ /^https/
 response = http.request(request)
end

它在本地运行良好,但是一旦我部署到 heroku,就会出现以下错误:

SocketError: getaddrinfo: Temporary failure in name resolution

关于如何解决这个问题的任何想法?

非常感谢您的帮助!!

编辑:这些是我在各自模型中包含的库:

require "net/http"
require "net/https"
require "uri"

这就是控制台在实际错误发生后向我抛出的内容:

from /usr/local/lib/ruby/1.9.1/net/http.rb:644:in `initialize'
from /usr/local/lib/ruby/1.9.1/net/http.rb:644:in `open'
from /usr/local/lib/ruby/1.9.1/net/http.rb:644:in `block in connect'
from /usr/local/lib/ruby/1.9.1/timeout.rb:44:in `timeout'
from /usr/local/lib/ruby/1.9.1/timeout.rb:89:in `timeout'
from /usr/local/lib/ruby/1.9.1/net/http.rb:644:in `connect'
from /usr/local/lib/ruby/1.9.1/net/http.rb:637:in `do_start'
from /usr/local/lib/ruby/1.9.1/net/http.rb:626:in `start'
from /usr/local/lib/ruby/1.9.1/net/http.rb:1168:in `request'
from /app/app/models/message.rb:224:in `send_post_request'
from /app/app/models/message.rb:46:in `opt_in_text'
from (irb):2
from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.6/lib/rails/commands/console.rb:47:in `start'
from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.6/lib/rails/commands/console.rb:8:in `start'
from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.6/lib/rails/commands.rb:41:in `<top (required)>'
4

1 回答 1

7

看起来连接暂时失败,也许在您的功能中重试?

def self.send_post_request(domain, data, retry_attempts=0)
  uri = URI.parse(domain)
  http = Net::HTTP.new(uri.host, uri.port)
  request = Net::HTTP::Post.new(uri.request_uri)
  request.set_form_data(data)
  http.use_ssl = true if domain =~ /^https/
  response = http.request(request)
rescue SocketError => error
  if retry_attempts > 0
    retry_attempts -= 1
    sleep 5 
    retry
  end
  raise
end
于 2013-01-09T22:19:25.087 回答