2015-09-23 7 views
5

Sto cercando di inviare una richiesta HTTP utilizzando HTTParty con alcuni parametri,Rubino HTTParty - ottenere l'URL di reindirizzamento

Esempio:

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

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

Il REDIRECT_URL per questa particolare richiesta è http://example2.com

Quando ho provato l'URL http://example1.com?a=123&b=456 nel browser, esso reindirizza all'URL previsto con il valore di parametro aggiunto come http://example2.com?c=123trt58, ma quando l'ho fatto usando HTTParty, ricevo solo una risposta HTML.

Il mio requisito è quello di ottenere l'URL (http://example2.com?c=123trt58) fuori dalla risposta.

Grazie in anticipo.

risposta

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: Questo utilizza naty nativo ruby ​​HTTP.

2

per ottenere l'URL finale dopo un reindirizzamento usando HTTParty è possibile utilizzare:

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

# response should be 'http://example2.com?c=123trt58' 
+0

scelta giusta è res = HTTParty.head ("http://example1.com?a=123&b=456") HTTParty.get scaricherà tutti i contenuti anche questo è il video 100Mb file. –

+0

@ AivilsŠtoss dovresti postare come risposta – Stefan

4

Se non si vuole seguire redirect, ma ancora voglia di sapere dove la pagina reindirizza a (utile per i crawler web , per esempio), è possibile utilizzare 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 
0

leggermente corretta @ High6 risposta:

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

Ciò impedirà il download di risposta di grandi dimensioni. Basta leggere le intestazioni.

Problemi correlati