groovy中,您可以通过执行以下操作来实现oachim的建议:
String location = "url-of-webpage-A"boolean wasRedirected = falseString pageContent = nullwhile( location ) { new URL( location ).openConnection().with { con -> // We'll do redirects ourselves con.instanceFollowRedirects = false // Get the response pre, and the location to jump to (in case of a redirect) location = con.getHeaderField( "Location" ) if( !wasRedirected && location ) { wasRedirected = true } // Read the HTML and close the inputstream pageContent = con.inputStream.withReader { it.text } }}println "wasRedirected:$wasRedirected contentLength:${pageContent.length()}"如果您不想被重定向,并且想要第一页的内容,则只需执行以下操作:
String location = "url-of-webpage-A"String pageContent = new URL( location ).openConnection().with { con -> // We'll do redirects ourselves con.instanceFollowRedirects = false // Get the location to jump to (in case of a redirect) location = con.getHeaderField( "Location" ) // Read the HTML and close the inputstream con.inputStream.withReader { it.text }}if( location ) { println "Page wanted to redirect to $location"}println "Content was:"println pageContent


