Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/65952596/ruby-net-http-get-does-not-work-with-urls-but-works-with-uris-why

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...