Ruby net/http/get 不适用于 url,但适用于 uri为什么?

问题描述

我有一个 Ruby 代码

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,'/')

产生错误

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

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)

但它与 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)

那么,谁能解释一下有什么区别,为什么这么有效,以及 URI 有什么特别之处?

解决方法

不同之处在于您的 urlString 的一个实例,它恰好是一个 URL。但是因为只是一个简单的字符串所以没有什么特别的意义。

uriURI 的一个实例,它不仅是一个简单的字符串,而且已经分析了字符串中的 URL,现在它提供了几种优化的方法来返回 URL 的特定部分——比如协议、主机名、路径或查询参数。