You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby中Net::HTTP::Get传递URL路径参数时URI报错的解决求助

Ruby中Net::HTTP::Get处理含大括号的路径参数问题

报错原因是{}属于URI规范里的保留特殊字符,Ruby的URI.parse不会自动对其编码,直接写入URL会被判定为无效URI。解决核心是先对包含大括号的路径部分做URL编码,再构建请求。

方法1:直接使用编码后的URL

把{18497418000111}替换为编码后的%7B18497418000111%7D,直接写入URL:

require 'net/http'
require 'net/https'
require 'json'  

uri = URI.parse("https://cdpj.partners.bancointer.com.br/pix/v2/webhook/%7B18497418000111%7D")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri.request_uri)
request["Authorization"] = "Bearer #{'1fd64146-xxxx-xxxx-xxxx-xxxx997c170'}"
request["Accept"] = "application/vnd.bluebadge-api.v1+json"
response = http.request(request)

方法2:动态编码参数(适合参数为变量的场景)

用CGI.escape或URI.encode_www_form_component对包含大括号的内容编码,再拼接URL:

require 'net/http'
require 'net/https'
require 'json'
require 'cgi'

# 假设ID是变量,可动态替换
target_id = "18497418000111"
# 对带大括号的完整内容编码
encoded_part = CGI.escape("{#{target_id}}")
# 拼接成合法URI
uri = URI.parse("https://cdpj.partners.bancointer.com.br/pix/v2/webhook/#{encoded_part}")

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri.request_uri)
request["Authorization"] = "Bearer #{'1fd64146-xxxx-xxxx-xxxx-xxxx997c170'}"
request["Accept"] = "application/vnd.bluebadge-api.v1+json"
response = http.request(request)

方法3:用URI对象规范构建路径

通过URI对象分步设置主机和编码后的路径,更符合Ruby的URI使用规范:

require 'net/http'
require 'net/https'
require 'json'
require 'cgi'

target_id = "18497418000111"
encoded_part = CGI.escape("{#{target_id}}")

# 初始化URI主机
uri = URI("https://cdpj.partners.bancointer.com.br")
# 设置编码后的完整路径
uri.path = "/pix/v2/webhook/#{encoded_part}"

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
# 直接传入uri对象构建请求
request = Net::HTTP::Get.new(uri)
request["Authorization"] = "Bearer #{'1fd64146-xxxx-xxxx-xxxx-xxxx997c170'}"
request["Accept"] = "application/vnd.bluebadge-api.v1+json"
response = http.request(request)

注意:浏览器会自动对URL中的特殊字符编码,所以直接打开能正常工作,但Ruby的URI.parse严格遵循URI规范,必须手动完成编码。

内容的提问来源于stack exchange,提问作者Ademir Gomes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 16:05:24