【问题标题】:ruby httparty get response url or id after postruby httparty 在发布后获取响应 url 或 id
【发布时间】:2010-08-23 07:12:50
【问题描述】:

在发布后,如何在单独的脚本中使用 httparty 从 rails 项目获取响应 url 或 id?

红宝石脚本:

  HTTParty.post('http://localhost:3000/change_logs', parameters)

response.body 和所有其他的不显示 url 和响应 id

【问题讨论】:

    标签: ruby httparty


    【解决方案1】:

    两年后,我找到了一种从response 上的request 属性访问最后一个URI 的方法:

    url      = "http://example.com/redirects/to/www"
    response = HTTParty.get(url)
    response.request.last_uri.to_s
    # => "http://www.example.com"
    

    【讨论】:

    • 如果您想在不获取最终目的地正文的情况下执行此操作。即,如果您只想获取最终 URL,则可以将 HTTPParty.get 调用替换为 HTTParty.head(url, { :maintain_method_across_redirects => true })
    【解决方案2】:

    很遗憾,HTTParty 不保留该信息。当它遇到重定向时,它将跟随重定向并返回该请求的结果。它不会保存原始请求中的任何信息。

    好消息是,这样的行为(通常)是可以预测的。 Web 应用程序通常会在向 URL 发送请求后重定向到相同的内容。

    但如果你真的想这样做,你将不得不使用 Ruby 附带的 net/http 库。不过,它并不比 HTTParty 难多少,所以工作量也不大。

    【讨论】:

    • 感谢您的回复,这是有道理的 - 但是我确实找到了一种方法......虽然有点奇怪
    【解决方案3】:

    这对我有用,但可能有更好的方法来做到这一点..

    get_change_log_id = HTTParty.post('http://localhost:3000/change_logs.xml', parameters).to_a
    
    get_change_log_id.each do |r|
      r.each do |sub|
        sub2 = sub.to_a
          sub2.each do |s|
            if s.index "id"
              @change_log_id = s.to_s.sub(/[i]/, '').sub(/[d]/, '')
            end
          end
      end
    end
    

    【讨论】:

    • 是的,有一个更简单的方法:results = HTTParty.post('localhost:3000/change_logs.xml', parameters) change_log_id = results.parsed_response["change_log"].values_at("id")
    猜你喜欢
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多