更新时间:2023-11-27 18:28:10
在groovy中,您可以执行约阿希姆建议在做:
In groovy, you could do what Joachim suggests by doing:
String location = "url-of-webpage-A"
boolean wasRedirected = false
String pageContent = null
while( location ) {
new URL( location ).openConnection().with { con ->
// We'll do redirects ourselves
con.instanceFollowRedirects = false
// Get the response code, 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()}"
如果您不想被重定向,并且希望第一页的内容,你只需要做:
If you don't want to be redirected, and want the contents of the first page, you simply need to do:
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