Ruby HTTParty - 获取重定向的URL

Raj*_*ran 5 http httparty ruby-on-rails-4 ruby-2.2

我正在尝试使用带有一些参数的HTTParty发送HTTP请求,

例如:

GET URL: http://example1.com?a=123&b=456

response_to_get = HTTParty.get('http://example1.com?a=123&b=456')
Run Code Online (Sandbox Code Playgroud)

此特定请求的redirect_urlhttp://example2.com

当我http://example1.com?a=123&b=456在浏览器中尝试URL 时,它会重定向到预期的URL,并附加参数值http://example2.com?c=123trt58,但是当我使用HTTParty时,我只得到一个HTML响应.

我的要求是从响应中获取URL(http://example2.com?c=123trt58).

提前致谢.

Arm*_*n H 6

如果您不想遵循重定向,但仍然想知道页面重定向到的位置(例如,对于网络爬虫有用),则可以使用response.headers['location']

response = HTTParty.get('http://httpstat.us/301', follow_redirects: false)

if response.code >= 300 && response.code < 400
    redirect_url = response.headers['location']
end
Run Code Online (Sandbox Code Playgroud)


Aiv*_*oss 5

稍微纠正@High6的答案:

    res = HTTParty.head("example1.com?a=123&b=456")
    res.request.last_uri.to_s
Run Code Online (Sandbox Code Playgroud)

这将防止大量响应下载。只需阅读标题即可。


小智 1

require 'uri'
require 'net/http'

url = URI("https://<whatever>")

req = Net::HTTP::Get.new(url)
res = Net::HTTP.start(url.host, url.port, :use_ssl => true) {|http|
  http.request(req)
}

res['location']
Run Code Online (Sandbox Code Playgroud)

PS:这是使用本机 ruby​​ HTTP 库。