【问题标题】:How do I inspect the full URL generated by HTTParty?如何检查 HTTParty 生成的完整 URL?
【发布时间】:2015-05-13 16:31:19
【问题描述】:

我想查看 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


    【解决方案1】:

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

    【讨论】:

    • 是的,这实际上是从子类中复制的,所以设置了base_uri。我会纠正它。谢谢!
    • 啊,我明白了!我尝试了res.last_uri,但出现错误。我现在看到,包括 .response 会找到正确的对象。
    • 有效,但不会显示传递给 URL 的参数。
    【解决方案2】:

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

    class Example
      include HTTParty
      debug_output STDOUT
    end
    

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

    【讨论】:

    • 这真的很有用。我将接受@victorkohl 提供的答案,因为它更直接适用,但作为调试的一般方法,这很棒。
    • 我收到 NoMethodError: undefined method 'debug_output' for HTTParty:Module 错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 2020-06-04
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    相关资源
    最近更新 更多