简体   繁体   中英

Ruby net/http/get does not work with url's, but works with uri's. Why?

I have a Ruby code:

require 'net/http'
url = "https://stackoverflow.com/questions/65798852/how-do-i-set-an-electron-variable-at-compile-time"
response = Net::HTTP.get_response(url, '/')

Which produces errors:

getaddrinfo: nodename nor servname provided, or not known (SocketError)

and

Failed to open TCP connection to https://stackoverflow.com/questions/65798852/how-do-i-set-an-electron-variable-at-compile-time:80 (getaddrinfo: nodename nor servname provided, or not known) (SocketError)

But it works perfectly with uri:

require 'net/http'
url = "https://stackoverflow.com/questions/65798852/how-do-i-set-an-electron-variable-at-compile-time"
uri = URI(url)
response = Net::HTTP.get_response(uri)

So, could anyone explain what is the difference, why it works so, and what is so special about URI?

The difference is that your url is an instance of String which happens to be a URL. But because it is just a simple string is has no special meaning.

Whereas uri is an instance of URI which is not only a simple string but had the URL from the string already analyzed and it now offers several optimized methods to return specific parts of the URL – like the protocol, the hostname, the path or query parameters.

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