简体   繁体   中英

Why do I get “Errno::ECONNREFUSED” with 'net/http' in Rails?

I am trying to parse an XML file from a URL. When I try something like this:

require 'net/http'
require 'rubygems'
require 'xmlsimple'

url = 'http://my-address.com/xmltest/note.xml'
xml_data = Net::HTTP.get_response(URI.parse(url)).body

Everything works, but only when I do this outside of my Rails project. If I try including this file in my Rails 3 project and parsing it there, I get the error "Errno::ECONNREFUSED in [controller]" - Connection refused - connect(2) .

My problem is the following: I don't know how to install the net/http component. I am looking for it on http://www.rubygems.org , but I can't find it.

Net::HTTP is part of Ruby's standard library. You can use require 'net/http' to load it.

Rather than use Net::HTTP , which is fairly low-level for what you want to do, I'd recommend using Ruby's Open::URI .

If you are moving a lot of HTTP data, you might want to look into something like HTTPClient or Curb or Typhoeus, which are designed for heavy-weight use and save you the trouble of having to write it all using Net::HTTP .

Regarding the ECONNREFUSED error: you might want to capture the HTTPResponse returned from get_response , then check its status before trying to read the body. The way you're doing it now doesn't let you react to a failed request.

Looks like the problem is that you can't connect to the HTTP-server.
You could try checking that you can access the URL in a browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM