如何检查 HTTParty 生成的完整 URL?

问题描述 投票:0回答:4

我想查看 HTTParty gem 根据我的参数构建的完整 URL,无论是在提交之前还是之后,都没关系。

我也很乐意从响应对象中获取它,但我也看不出有什么方法可以做到这一点。

(一点背景)

我正在使用 HTTParty gem 为 API 构建一个包装器。它广泛工作,但偶尔我会从远程站点收到意外的响应,我想深入了解原因 - 是我发送的内容不正确吗?如果是这样,那又怎样?我是否以某种方式扭曲了请求?查看原始 URL 对于故障排除很有帮助,但我不知道如何进行。

例如:

HTTParty.get('http://example.com/resource', query: { foo: 'bar' })

大概会生成:

http://example.com/resource?foo=bar

但是我怎样才能检查这个呢?

在一个例子中,我这样做了:

HTTParty.get('http://example.com/resource', query: { id_numbers: [1, 2, 3] }

但是没有成功。通过实验,我能够生产出有效的产品:

HTTParty.get('http://example.com/resource', query: { id_numbers: [1, 2, 3].join(',') }

很明显,HTTParty 形成查询字符串的默认方法与 API 设计者的首选格式不一致。很好,但是弄清楚到底需要什么是很尴尬的。

ruby-on-rails ruby httparty
4个回答
32
投票

您没有在示例中传递基本 URI,因此它不起作用。

更正一下,您可以像这样获取整个 URL:

res = HTTParty.get('http://example.com/resource', query: { foo: 'bar' })
res.request.last_uri.to_s
# => "http://example.com/resource?foo=bar" 

使用类:

class Example
  include HTTParty
  base_uri 'example.com'

  def resource
    self.class.get("/resource", query: { foo: 'bar' })
  end
end

example = Example.new
res = example.resource
res.request.last_uri.to_s
# => "http://example.com/resource?foo=bar" 

12
投票

首先设置即可看到HTTParty发送的所有请求信息:

class Example
  include HTTParty
  debug_output STDOUT
end

然后它会将请求信息(包括 URL)打印到控制台。


0
投票

正如here所解释的,如果您需要在发出请求之前获取URL,您可以这样做

HTTParty::Request.new(:get, '/my-resources/1', query: { thing: 3 }).uri.to_s

0
投票

这是对我有帮助的人:

HTTParty::Basement.debug_output $stdout
© www.soinside.com 2019 - 2024. All rights reserved.