2011-09-14 45 views
4

我想提取網頁A的內容使用Groovy我已經試過以下如何以編程方式檢查頁面的url是否重定向?

...... 
String urlStr = "url-of-webpage-A" 
String pageText = urlStr.toURL().text 
//println pageText 
..... 

上面的代碼,只要它不重定向到其他網頁檢索網頁上的文本B.如果A重定向到B,則在pageText變量中檢索webPage B的頁面內容。有沒有一種方法來編碼和檢查網頁A是否重定向到其他網頁(在常規或Java)?

PS:上述片的代碼不是服務器側邏輯的一部分。我在桌面應用程序的範圍內在客戶端執行它。

回答

4

在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  
+0

喜添,我想上面的代碼,但它仍然是檢索新的位置/重定向網頁的內容。 :(我需要原始頁面的內容。 –

+1

@VeeKay哦...我想你想的最後一頁的內容,但是要知道你重定向...我添加了一個不同的方法,做什麼,我希望你自找的... –

相關問題