在Groovy中,你可以做的做什麼Joachim suggests:
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()}"
如果您不希望被重定向,並且希望在第一頁的內容,你只需要做:
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
喜添,我想上面的代碼,但它仍然是檢索新的位置/重定向網頁的內容。 :(我需要原始頁面的內容。 –
@VeeKay哦...我想你想的最後一頁的內容,但是要知道你重定向...我添加了一個不同的方法,做什麼,我希望你自找的... –