Ruby HTTParty - Get Redirected URL

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

For instance:

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

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

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

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

Thanks at Advance.

+5
source share
5 answers

If you do not want to follow the redirect, but still want to know which page is redirected (for example, for web crawlers), 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 
+4
source

To get the final URL after redirecting 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' 
+2
source
 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 uses its own Ruby HTTP lib.

+1
source

Lightly corrected answer @ High6:

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

This will prevent downloading large responses. Just read the headlines.

0
source

You can try ruby ​​gem final_redirect_url

0
source

Source: https://habr.com/ru/post/1232071/


All Articles