6

I am trying to send an HTTP request using HTTParty with some parameters,

Eg:

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

response_to_get = HTTParty.get('http://example1.com?a=123&b=456')

The redirect_url for this particular request is http://example2.com

When I tried the URL http://example1.com?a=123&b=456 in browser, it redirects to the expected URL with parameter value appended to it like http://example2.com?c=123trt58, but when I did it using HTTParty, I'm getting an HTML reponse only.

My requirement is to get the URL(http://example2.com?c=123trt58) out from the response.

Thanks in Advance.

Rajesh Omanakuttan
  • 6,788
  • 7
  • 47
  • 85

4 Answers4

9

If you do not want to follow redirects, but still want to know where the page is redirecting to (useful for web crawlers, for example), you can use 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
Arman H
  • 5,488
  • 10
  • 51
  • 76
5

Slightly corrected @High6 answer:

    res = HTTParty.head("example1.com?a=123&b=456")
    res.request.last_uri.to_s

This will prevent large response download. Just read headers.

Aivils Štoss
  • 858
  • 11
  • 9
2

To get the final URL after a redirect using HTTParty you can use:

res = HTTParty.get("http://example1.com?a=123&b=456")
res.request.last_uri.to_s

# response should be 'http://example2.com?c=123trt58'
disco crazy
  • 31,313
  • 12
  • 80
  • 83
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']

PS: This is using native ruby HTTP lib.

Stefan
  • 109,145
  • 14
  • 143
  • 218
jef
  • 51
  • 1
  • 5