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

How do I inspect the full URL generated by HTTParty?

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

我也很乐意从响应对象中获取它,但我也看不到这样做的方法。

(有点背景)

我正在使用 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 设计师的首选格式不一致。很好,但是很难弄清楚到底需要什么。

您没有在您的示例中传递基本 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:

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" 

您可以通过第一个设置查看HTTParty发送的所有请求信息:

class Example
  include HTTParty
  debug_output STDOUT
end

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