题
如果我有网址(例如 http://www.foo.com/ alink.pl?page=2 ),我想确定我是否被重定向到另一个链接。我也想知道最终的URL(例如 http://www.foo.com/other_link。 PL )。最后,我希望能够在Perl和Groovy中执行此操作。
解决方案
Perl:
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $request = HTTP::Request->new( GET => 'http://google.com/' );
my $response = $ua->request($request);
if ( $response->is_success and $response->previous ) {
print $request->url, ' redirected to ', $response->request->uri, "\n";
}
其他提示
好吧,我对Perl或groovy一无所知,所以我会从HTTP的角度给你另一个,你必须适应。
通常,您发出HTTP请求,然后返回一些HTML文本以及响应代码。 Success的响应代码是200.300范围内的任何响应代码都是某种形式的重定向。
参考James的回答 - 示例HTTP会话:
$ telnet www.google.com 80
HEAD / HTTP/1.1
HOST: www.google.com
HTTP/1.1 302 Found
Location: http://www.google.it/
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Set-Cookie: ##############################
Date: Thu, 30 Oct 2008 20:03:36 GMT
Server: ####
Content-Length: 218
使用HEAD而不是GET只能得到标题。 " 302"表示临时重定向,“位置:”是您被重定向到的地方。
快速&脏groovy脚本来显示概念 - 注意,这是使用 java.net.HttpURLConnection
为了检测重定向,您必须使用 setFollowRedirects(false)
。否则,无论如何,您最终都会使用 responseCode
200来重定向页面。缺点是您必须自己导航重定向。
URL url = new URL ('http://google.com')
HttpURLConnection conn = url.openConnection()
conn.followRedirects = false
conn.requestMethod = 'HEAD'
println conn.responseCode
// Not ideal - should check response code too
if (conn.headerFields.'Location') {
println conn.headerFields.'Location'
}
301
["http://www.google.com/"]
在Perl中,您可以使用 LWP :: Useragent 为此。我想最简单的方法是使用 add_handler
添加 response_redirect
处理程序。
我认为这适用于301重定向。
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $request = HTTP::Request->new( GET => 'http://google.com/' );
my $response = $ua->request($request);
if ( $response->is_redirect ) {
print $request->url . " redirected to location " . $response->header('Location') . "\n";
}
不隶属于 StackOverflow